Imitating a static method

This question already has an answer here:

  • Static methods in Python? 8 answers

  • You should use @classmethod :

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

    The difference between a classmethod and a staticmethod is that the latter knows nothing about its enclosing class, whereas the former does (via the cls argument). A staticmethod can just as easily be declared outside the class.

    If you don't want show() to know anything about C , either use @staticmethod or declare show() outside of C .


    The idiomatic translation of a static method from other languages is usually a module-level method.

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

    The answers telling you that python has @staticmethod s are correct, and also misleading: it is usually correct to just use a module-level function.


    你应该使用@staticmethod

    @staticmethod
    def show(message):
        print("The message is: {}".format(message))
    
    链接地址: http://www.djcxy.com/p/55134.html

    上一篇: 为什么pycharm建议将方法更改为static

    下一篇: 模仿静态方法