Python - 继承旧式类 [英] Python - inheriting from old-style classes

查看:212
本文介绍了Python - 继承旧式类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过telnet连接到实验室仪器。我想从标准库中的 telnetlib 模块扩展 Telnet 类,以包含特定于我们的函数工具:

I am trying to connect via telnet to a laboratory instrument. I'd like to extend the Telnet class from the telnetlib module in the standard library, to include functions specific to our instrument:

import telnetlib
class Instrument(telnetlib.Telnet):
    def __init__(self, host=None, port=0, timeout=5):
        super(Instrument,self).__init__(host, port, timeout)

我在这段代码中尝试做的只是继承父类的 __ init __ 方法( telnetlib。 Telnet )并传递标准参数,因此我可以稍后向 __ init __ 添加内容。这个公式在其他场合对我有用;这次当我尝试实例化时,它在 super()语句中给出了一个错误:

All I am trying to do in this code is inherit the __init__ method from the parent class (telnetlib.Telnet) and pass on the standard arguments, so I can add things to __init__ later. This formula has worked for me on other occasions; this time it gives me an error at the super() statement when I try to instantiate:

TypeError: must be type, not classobj

我查看了源代码telnetlib和Telnet似乎是一个旧式类(它不继承自对象) - 我想知道这是否可能是我的问题的根源?如果是这样,怎么能克服?我已经看到了一些代码示例,其中派生类继承了超类和对象,但我不完全确定这是否是对我同样问题的响应。

I looked at the source code for telnetlib, and Telnet appears to be an old-style class (it doesn't inherit from object) - I'm wondering if this could be the source of my problem? If so, how can it be overcome? I've seen some code examples where the derived class inherits both from the superclass and object, though I'm not entirely sure if this is a response to the same problem as me.

完全披露:我也尝试使用 telnetlib.Telnet 代替 super ()和来自telnetlib的导入Telnet ,用 Telnet 代替超级()。在这些情况下问题仍然存在。

Full disclosure: I have also tried using telnetlib.Telnet in place of super(), and from telnetlib import Telnet with Telnet in place of super(). The problem persists in these cases.

谢谢!

推荐答案

你需要像这样调用构造函数

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

您需要添加显式 self ,因为 telnet.Telnet .__ init __ 是不是绑定方法而是未绑定方法,即没有分配实例。因此,在调用它时,您需要明确地传递实例。

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)

这篇关于Python - 继承旧式类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆