[英]Python - inheriting from old-style classes
我試圖通過telnet連接到實驗室儀器。 我想從標准庫中的telnetlib
模塊擴展Telnet
類,以包含特定於我們儀器的函數:
import telnetlib
class Instrument(telnetlib.Telnet):
def __init__(self, host=None, port=0, timeout=5):
super(Instrument,self).__init__(host, port, timeout)
我在這段代碼中嘗試做的就是從父類( telnetlib.Telnet
)繼承__init__
方法並傳遞標准參數,所以我可以稍后向__init__
添加內容。 這個公式在其他場合對我有用; 這次當我嘗試實例化時,它在super()
語句中給出了一個錯誤:
TypeError: must be type, not classobj
我查看了telnetlib的源代碼,Telnet似乎是一個舊式類(它不是從object
繼承) - 我想知道這是否可能是我的問題的根源? 如果是這樣,怎么可以克服? 我已經看到了一些代碼示例,其中派生類繼承了超類和object
,但我不完全確定這是否是對我的同一問題的響應。
完全披露:我也嘗試使用telnetlib.Telnet
代替super()
,並from telnetlib import Telnet
和Telnet
代替super()
。 在這些情況下問題仍然存在。
謝謝!
你需要像這樣調用構造函數 :
telnetlib.Telnet.__init__(self, host, port, timeout)
你需要添加顯式self
因為telnet.Telnet.__init__
不是綁定方法 ,而是一個未綁定的方法 ,即沒有分配實例。 因此,在調用它時,您需要明確地傳遞實例。
>>> Test.__init__
<unbound method Test.__init__>
>>> Test().__init__
<bound method Test.__init__ of <__main__.Test instance at 0x7fb54c984e18>>
>>> Test.__init__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method __init__() must be called with Test instance as first argument (got nothing instead)
您必須從object
繼承,並且必須將它放在您嘗試繼承的舊式類之后(以便首先找不到object
的方法):
>>> class Instrument(telnetlib.Telnet,object):
... def __init__(self, host=None, port=0, timeout=5):
... super(Instrument,self).__init__(host, port, timeout)
...
>>> Instrument()
<__main__.Instrument object at 0x0000000001FECA90>
繼承自object為您提供了一個與super
工作的新式類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.