Imitating a static method
本问题已经有最佳答案,请猛点这里访问。
这是模仿Python中静态方法的正确方法吗?python允许静态方法吗?
1 2 3 4 5 6 7 | class C(object): def show(self,message): print("The message is: {}".format(message)) m ="Hello World!" C.show(C,message=m) |
静态方法与其他语言的惯用翻译通常是模块级方法。
1 2 | def show(message): print("The message is: {}".format(message)) |
告诉您python有
你应该使用
1 2 3 | @staticmethod def show(message): print("The message is: {}".format(message)) |
您应该使用
1 2 3 | @classmethod def show(cls, message): print("The message is: {}".format(message)) |
如果你不想让
您可以使用decorator
if a class method is called for a derived class, the derived class
object is passed as the implied first argument (http://docs.python.org/3.3/library/functions.html#classmethod).
1 2 3 4 5 6 7 8 9 10 11 12 | class C1(object): @classmethod def show(cls,message): print("[{}] The message is: {}".format(cls,message)) class C2(C1): pass m ="Hello World!" C2.show(message=m) # vs. C1.show(message=m) with output [<class '__main__.C1'>] The message is: Hello World! |