python - new.instancemethod 在重载脚本中转换为 python 3.3

标签 python python-3.x

我想首先说我知道new.instancemethod Python 3 中不存在重载函数,从技术上讲也不存在重载函数。

但是,我正在查看一个旧的 python 包,它使用 new.instancemethod在有效允许 overloaded functions 的脚本中。

具体包可以从 this site 找到尽管我已经包含了我认为是以下相关部分的内容。

我正在使用 python 3,因此我需要将其转换为 python 3 的可用脚本。我已经使用了 2to3 工具并已经查看了大部分更改。但是,我被困在下面,我不知道要替换什么 new.instancemethod和。

class overloaded:
    ...

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        return new.instancemethod(self, obj)

__init__前面使用了类重载作为装饰器,不会造成任何问题,但是当它在方法前面使用时就会出现问题,因为 obj不再是None .

我需要这个的原因是,a) 它很有用,b) 因为我目前正在将过时的 IbPy 包从 2.56 翻译到 3.x。 IbPy 包基本上是将 Interactive Brokers 的 Java API 翻译成 Python。

@overloaded前面的main方法如下:

@overloaded
@synchronized(mlock)
def eConnect(self, host, port, clientId):
    host = self.checkConnected(host)
    if host is None:
        return
    try:
        socket = Socket(host, port)
        self.eConnect(socket, clientId)
    except Exception as e:
        self.eDisconnect()
        self.connectionError()

请注意,@synchronize 只是一个强制多个函数同步的装饰器。代码很短,可以找到here ,尽管我认为这与我的问题无关。

经过这么长的解释,我如何得到 return new.instancemethod(self, obj)想了解更多 python 3 吗?尽管我昨晚和今天早上都读了相关内容,但我似乎无法理解正在发生的事情。我已经尝试了很多事情,我想我只是缺乏对 python 如何处理这个问题的理解。

如有任何建议,我们将不胜感激。谢谢!

最佳答案

应该使用

types.MethodType 而不是 new.instancemethod

或者您可以从任何类获取实例方法:

instancemethod = type(Anyclass.method)

其中 method 是任何类方法

Adding a Method to an Existing Object Instance

关于python - new.instancemethod 在重载脚本中转换为 python 3.3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16266949/

相关文章:

python - 我怎样才能重复播放一个声音样本,让下一个循环与前一个循环重叠

python - 无法为 python-docx 中的文本设置 "right to left"对齐样式

python - 查找并替换属于不同单词但不是子字符串的字符串?

python - 您可以从第 n 个元素开始完全循环遍历一个范围吗?

javascript - 如何在网页中执行 "javascript:__doPostBack"以使用 selenium 下载 pdf 文件?

python-3.x - Google Cloud Functions for Python 中的 tmp 文件

mysql - 为什么 Python 子进程不能像预期的那样使用 named_pipe?

python - Eclipse 有缩进指南吗?

python - 使用 `K.constant` 或 `self.add_weight(trainable=False)` 作为层中的固定权重有什么不同

与目录同名的 Python 导入类