gpt4 book ai didi

python - 更换 "new"模块

转载 作者:太空狗 更新时间:2023-10-29 22:06:04 28 4
gpt4 key购买 nike

我的代码中包含以下两行:-

instanceMethod = new.instancemethod(testFunc, None, TestCase)
setattr(TestCase, testName, instanceMethod)

不使用"new"模块怎么能重写呢?我确信新样式类为此提供了某种解决方法,但我不确定如何解决。

最佳答案

有一个讨论表明在 python 3 中,这不是必需的。同样适用于 Python 2.6

参见:

>>> class C: pass
...
>>> c=C()
>>> def f(self): pass
...
>>> c.f = f.__get__(c, C)
>>> c.f
<bound method C.f of <__main__.C instance at 0x10042efc8>>
>>> c.f
<unbound method C.f>
>>>

为了包括我在内的每个人的利益重申这个问题。

Python3 中是否有 new.instancemethod 的替代品?也就是说,给定一个任意实例(不是它的类),我如何添加一个新的适当定义的函数作为它的方法?

所以下面应该足够了:

TestCase.testFunc = testFunc.__get__(None, TestCase)

关于python - 更换 "new"模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4364565/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com