在模块a.py
def task():
print "task called"
a = task
class A:
func = task # this show error unbound method
#func = task.__call__ # if i replace with this work
def __init__(self):
self.func_1 = task
def test_1(self):
self.func_1()
@classmethod
def test(cls):
cls.func()
a()
A().test_1()
A.test()
输出:
task called
task called
Traceback (most recent call last):
File "a.py", line 26, in <module>
A.test()
File "a.py", line 21, in test
cls.func()
TypeError: unbound method task() must be called with A instance as
first argument (got nothing instead)
在模块中,我可以轻松地将函数分配给变量。当在类内部尝试将模块级函数分配给类变量func = task时,它会显示错误,要删除此错误,我必须将其替换为func = task.__call__ 但是当我将其分配给实例变量时,它的工作self.func_1 = task。
我的问题是:为什么我不能在没有 __call__的情况下将模块级函数分配给类变量,而当我可以分配给实例变量的同一个函数正在工作时。