对于以下代码:
import os.path
class Test:
@classmethod
def foo(cls):
cls.exist = os.path.exists
print type(cls.exist)
print type(os.path.exists)
def main():
Test.foo()
我得到的输出为:
<type 'instancemethod'>
<type 'function'>
我只是将函数 os.path.exist 分配给类变量 cls.exist。 但是当我打印这两个变量时,我得到一个作为实例方法,另一个作为函数。 为什么 ?
最佳答案
您可能将其分配为类变量,但它绑定(bind)到类:
Traceback (most recent call last):
File "<stdin>", line 12, in <module>
TypeError: unbound method exists() must be called with Test instance as first argument (got str instance instead)
您需要使 exist
成为 staticmethod
才能使其“独立于”类:
cls.exist = staticmethod(os.path.exists)
现在,两者属于同一类型:
<type 'function'>
<type 'function'>
你实际上可以这样调用它:
>>> Test.exist('foo')
False
关于python - 类方法和类方法中定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16067188/