Home  >  Article  >  Backend Development  >  What is the difference between decorators @staticmethod and @classmethod

What is the difference between decorators @staticmethod and @classmethod

anonymity
anonymityOriginal
2019-05-24 14:58:206465browse

The difference between decorators @staticmethod and @classmethod is: @staticmethod does not require self and cls parameters, @classmethod does not require self parameters, but requires cls parameters.

What is the difference between decorators @staticmethod and @classmethod

Generally speaking, when we use a method of a class, we must first instantiate the class, and then use the instantiated class to call its method

class Test(object):
    """docstring for Test"""
    def __init__(self, arg=None):
        super(Test, self).__init__()
        self.arg = arg
    def say_hi(self):
        print 'hello wrold'
def main():
    test = Test() //1. 首先实例化test类
    test.say_hi() //2. 再调用类的方法
if __name__ == '__main__':
    main()

When using @staticmethod or @classmethod, you can call it directly by class name.method name () without instantiation.

This helps organize the code, put certain functions that should belong to a certain class into that class, and also helps keep the namespace tidy.

class Test(object):
    """docstring for Test"""
    def __init__(self, arg=None):
        super(Test, self).__init__()
        self.arg = arg
    def say_hi(self):
        print 'hello wrold'
    @staticmethod
    def say_bad():
        print 'say bad'
    @classmethod
    def say_good(cls):
        print 'say good'
def main():
    test = Test()
    test.say_hi()
    Test.say_bad() //直接类名.方法名()来调用
    Test.say_good() //直接类名.方法名()来调用
if __name__ == '__main__':
    main()

The difference between @staticmethod or @classmethod

is an ordinary method of a class, and one parameter requires the self parameter to represent itself.

@staticmethod does not need to represent the self of its own object and the cls parameter of its own class, just like using a function.

@classmethod does not require the self parameter, but the first parameter needs to be the cls parameter representing its own class.

The above is the detailed content of What is the difference between decorators @staticmethod and @classmethod. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn