小编Ale*_*bes的帖子

当@classmethod是什么时,为什么@staticmethod不会跨类保留?

采用以下示例脚本:

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

23
推荐指数
2
解决办法
1055
查看次数