模仿静态方法

时间:2013-08-13 14:14:34

标签: python python-3.x

这是在Python中模仿静态方法的正确方法吗? Python允许静态方法吗?

class C(object):

    def show(self,message):
        print("The message is: {}".format(message))

m = "Hello World!"
C.show(C,message=m)

The message is: Hello World!

4 个答案:

答案 0 :(得分:3)

静态方法与其他语言的惯用翻译通常是模块级方法。

def show(message):
    print("The message is: {}".format(message))

答案告诉你python有@staticmethod是正确的,也有误导性:通常使用模块级函数是正确的。

答案 1 :(得分:2)

您应该使用@classmethod

@classmethod
def show(cls, message):
        print("The message is: {}".format(message))

classmethodstaticmethod之间的区别在于后者对其封闭类一无所知,而前者则(通过cls参数)知道。 staticmethod可以很容易地在课堂外声明。

如果您不希望show()了解C的任何内容,请使用@staticmethod或在show()之外声明C

答案 2 :(得分:2)

您应该使用@staticmethod

@staticmethod
def show(message):
    print("The message is: {}".format(message))

答案 3 :(得分:1)

您可以使用装饰器@classmethod。这不会造成问题。另外

  

如果为派生类调用类方法,则派生类   object作为隐含的第一个参数(http://docs.python.org/3.3/library/functions.html#classmethod)传递。

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!

[<class '__main__.C2'>] The message is: Hello World!