类变量的行为与正则变量不同。将类变量作为方法调用时,不会像调用正则变量一样调用它:
#!/usr/bin/env python
def func():
print 'func called'
class MyClass(object):
FUNC = func
def call_func(self):
MyClass.FUNC()
instance = MyClass()
instance.call_func()
产生:
Traceback (most recent call last):
File "main.py", line 12, in <module>
instance.call_func()
File "main.py", line 9, in call_func
MyClass.FUNC()
TypeError: unbound method func() must be called with MyClass instance as first argument (got nothing instead)
在我看来,这是一个非常简单的解决方案:
区别在于,调用
MyClass.FUNC()
时,应该传递实例要使其按预期工作,必须用
staticmethod()
装饰FUNC
:相关问题 更多 >
编程相关推荐