python ordinary methods, @classmethod, @staticmethod

  • Ordinary method
    Instantiate a class, and then call the method through the instantiation of the class:

    class method1:
    def __init__(self):
        self.items = [1,2,3,]
    def getvalue(self):
        return self.items
  • @classmedhod
    depends on the class but not on the example. When defining a method, the first parameter refers to the current class

    class method2:
    item = 1
    def __init__(self):
        self.items = [1,2,3,]
    @classmethod
    def getvalue(cls, args):
        print(cls.__name__)   # print: method2
        print(cls.item)             # print: 1
        return cls
  • @staticmedhot
    static method, consistent with java, C#, but defined in the class, has nothing to do with the class

    class method3:
    item  = 1
    @staticmethod
    def getvalue():
        print(item)      # error

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325113109&siteId=291194637