我是python的新手,我不太了解__func__python 2.7.
我知道什么时候定义这样的类:
class Foo:
def f(self, arg):
print arg
Run Code Online (Sandbox Code Playgroud)
我可以使用Foo().f('a')或Foo.f(Foo(), 'a')调用此方法.但是,我无法通过此方法调用此方法Foo.f(Foo, 'a').但我意外地发现我可以使用Foo.f.__func__(Foo, 'a')甚至Foo.f.__func__(1, 'a')获得相同的结果.
我打印出的值Foo.f,Foo().f和Foo.f.__func__,它们都是不同的.但是,我在定义中只有一段代码.谁可以帮助解释上面的代码实际上是如何工作的,特别是__func__?我现在真的很困惑.
给定两个不相关的类A和B,如何A.method使用B的对象调用self?
class A:
def __init__(self, x):
self.x = x
def print_x(self):
print self.x
class B:
def __init__(self, x):
self.x = x
a = A('spam')
b = B('eggs')
a.print_x() #<-- spam
<magic>(A.print_x, b) #<-- 'eggs'
Run Code Online (Sandbox Code Playgroud) 为什么在下面的代码中,使用类变量作为方法指针会导致未绑定的方法错误,而使用普通变量可以正常工作:
class Cmd:
cmd = None
@staticmethod
def cmdOne():
print 'cmd one'
@staticmethod
def cmdTwo():
print 'cmd two'
def main():
cmd = Cmd.cmdOne
cmd() # works fine
Cmd.cmd = Cmd.cmdOne
Cmd.cmd() # unbound error !!
if __name__=="__main__":
main()
Run Code Online (Sandbox Code Playgroud)
完整的错误:
TypeError: unbound method cmdOne() must be called with Cmd instance as
first argument (got nothing instead)
Run Code Online (Sandbox Code Playgroud)