采用以下示例脚本:
class A(object):
@classmethod
def one(cls):
print("I am class")
@staticmethod
def two():
print("I am static")
class B(object):
one = A.one
two = A.two
B.one()
B.two()
Run Code Online (Sandbox Code Playgroud)
当我使用Python 2.7.11运行此脚本时,我得到:
I am class
Traceback (most recent call last):
File "test.py", line 17, in <module>
B.two()
TypeError: unbound method two() must be called with B instance as first argument (got nothing instead)
Run Code Online (Sandbox Code Playgroud)
似乎@classmethod装饰器在类中保留,但@staticmethod不是.
Python 3.4的行为符合预期:
I am class
I am static
Run Code Online (Sandbox Code Playgroud)
为什么Python2不能保留@staticmethod,是否有解决方法?
编辑:从课堂上取两个(并保留@staticmethod)似乎有效,但这对我来说似乎仍然很奇怪.
python static-methods class-method python-2.7 python-descriptors