2015-08-22 84 views
0

我很新的python,目前正在玩zeroconf庫。python這是什麼數據類型?

當我嘗試到網絡上,我看到這個在函數定義上註冊一個服務:

def register_service(self, info, ttl=_DNS_TTL): 
    """Registers service information to the network with a default TTL 
    of 60 seconds. Zeroconf will then respond to requests for 
    information for that service. The name of the service may be 
    changed if needed to make it unique on the network.""" 
    self.check_service(info) 
    self.services[info.name.lower()] = info 
    if info.type in self.servicetypes: 
     self.servicetypes[info.type] += 1 
    else: 
     self.servicetypes[info.type] = 1 
    now = current_time_millis() 
    next_time = now 
    i = 0 
    while i < 3: 
     if now < next_time: 
      self.wait(next_time - now) 
      now = current_time_millis() 
      continue 
     out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) 
     out.add_answer_at_time(DNSPointer(info.type, _TYPE_PTR, 
              _CLASS_IN, ttl, info.name), 0) 
     out.add_answer_at_time(DNSService(info.name, _TYPE_SRV, 
              _CLASS_IN, ttl, info.priority, info.weight, info.port, 
              info.server), 0) 
     out.add_answer_at_time(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 
             ttl, info.text), 0) 
     if info.address: 
      out.add_answer_at_time(DNSAddress(info.server, _TYPE_A, 
               _CLASS_IN, ttl, info.address), 0) 
     self.send(out) 
     i += 1 
     next_time += _REGISTER_TIME 

任何人都知道什麼類型的info的意思是什麼?

編輯
感謝提供,這是一個ServiceInfo類的答案。除了文檔字符串在人們搜索時提供這個答案的事實。我還是不明確的:

  • 過程中遇到這種情況時,專家Python程序員遵循 - 文檔字符串的時候沒有采取什麼措施來找到info數據類型說呢?
  • python解釋器如何知道info是ServiceInfo類的,當我們沒有指定類類型作爲register_service的輸入參數的一部分?它如何知道info.type是一個有效的屬性,並且說info.my_property不是?
+0

你在哪裏看到這個定義?我似乎無法找到'register_service'在https://github.com/wmcbrine/pyzeroconf – ryachza

+0

我要添加'info .__ class__'到'register_service'函數,但我不能調用該函數作爲' info'是一個輸入參數。任何其他方式我可以調用該函數?如果我添加了'info = None',它會使數據類型失效嗎? – snowbound

+0

哎呀,對不起@ZJM。錯誤的鏈接。這是正確的:https://github.com/jstasiak/python-zeroconf – snowbound

回答

2

它是ServiceInfo類的一個實例。

從閱讀代碼和docstrings可以推斷出它。 register_service調用check_service函數,我引用「檢查網絡中唯一的服務名稱,修改傳入的ServiceInfo是否不唯一」。

+0

hi @Alik。你看到了哪些文檔?我在'zeroconf.py'模塊中搜索了'info'的所有實例,並且找不到它的正確定義。只看到它用。 (點)符號,例如'info.type','info.address' – snowbound

+0

@snowbound我已經更新了我的答案 – Alik

+2

@snowbound:歡迎來到動態語言的世界!你應該從這裏拿回家,就是在自己的代碼中編寫出好的文檔,記錄不明顯的數據類型。 :) –

1

它看起來應該是ServiceInfo。發現在倉庫中的例子:

https://github.com/jstasiak/python-zeroconf/blob/master/examples/registration.py

編輯

  1. 我真的不知道該說些什麼,除了「什麼辦法,我要」。在實踐中,我無法真正記得接口合約未被完全清楚的時候,因爲這只是使用Python的一部分。由於這個原因,文檔更多是要求
  2. 簡短的回答是,「它不」。 Python使用「鴨子打字」的概念,其中任何支持合同必要操作的對象都是有效的。你可以給它任何值的代碼使用所有的屬性,它不知道區別。因此,根據第1部分,最糟糕的情況是,您只需要追蹤對象的每次使用情況,並提供滿足所有要求的對象,並且如果您錯過了某個部分,則會收到運行時錯誤任何使用它的代碼路徑。

我的偏好也適用於靜態打字。很大程度上,我認爲使用動態類型進行文檔和單元測試會變得「更難的要求」,因爲編譯器無法爲您完成任何工作。

+0

嗨@ryachza,我已經更新了我的原始問題,以說出我不是清楚(對不起,我的背景是強類型/編譯語言) – snowbound