Python - inheriting from old-style classes

旧巷老猫 提交于 2019-11-29 05:26:22

You need to call the constructor like this:

telnetlib.Telnet.__init__(self, host, port, timeout)

You need to add the explicit self since telnet.Telnet.__init__ is not a bound method but rather an unbound method, i.e. witout an instance assigned. So when calling it you need to pass the instance explicitely.

>>> 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)

You have to inherit from object, and you must put it after the old-style class you are trying to inherit from (so that object's methods aren't found first):

>>> 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>

Inheriting from object gives you a new-style class which works with super.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!