替换"新"模块

6 python python-3.x

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

instanceMethod = new.instancemethod(testFunc, None, TestCase)
setattr(TestCase, testName, instanceMethod)
Run Code Online (Sandbox Code Playgroud)

如何在不使用"新"模块的情况下重写?我确定新的样式类为此提供了某种解决方法,但我不确定如何.

pyf*_*unc 10

有一个讨论表明在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>
>>> 
Run Code Online (Sandbox Code Playgroud)

重申每个人的利益,包括我的利益.

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

所以下面就足够了:

TestCase.testFunc = testFunc.__get__(None, TestCase)
Run Code Online (Sandbox Code Playgroud)


Oli*_*ver 5

您可以将“new.instancemethod”替换为“types.MethodType”:

from types import MethodType as instancemethod

class Foo: 
    def __init__(self):
        print 'I am ', id(self)

def bar(self): 
    print 'hi', id(self)

foo = Foo()  # prints 'I am <instance id>'
mm = instancemethod(bar, foo) # automatically uses foo.__class__
mm()         # prints 'I have been bound to <same instance id>'

foo.mm       # traceback because no 'field' created in foo to hold ref to mm
foo.mm = mm  # create ref to bound method in foo
foo.mm()     # prints 'I have been bound to <same instance id>'
Run Code Online (Sandbox Code Playgroud)