Characteristics and differences between static methods and class methods

1. Class attributes, instance attributes

  • The difference is with: the location saved in memory is different
  • Instance properties belong to the object
  • class attribute belongs to class
  • Instance properties need to be accessed through objects, and class properties are accessed through classes
  • Only one copy of class attributes is stored in memory, and one copy of instance attributes is stored in each object - when creating instance objects through classes, if each object needs attributes with the same name, then use class attributes and use one copy Just

2. Instance methods, static methods, and class methods

  • All three methods belong to the class in memory, but they are called differently
  • Instance method: called by the object; at least one self parameter; when the instance method is executed, the object that calls the method is automatically assigned to self; class method: called by the class; at least one cls parameter; when the class method is executed, the method will be automatically called The class is assigned to cls; static method: called by the class; no default parameters;
class Foo(object):
    def __init__(self, name):
        self.name = name

    def ord_func(self):
        """ 定义实例方法,至少有一个self参数 """
        # print(self.name)
        print('实例方法')

    @classmethod
    def class_func(cls):
        """ 定义类方法,至少有一个cls参数 """
        print('类方法')

    @staticmethod
    def static_func():
        """ 定义静态方法 ,无默认参数"""
        print('静态方法')



f = Foo("中国")
# 调用实例方法
f.ord_func()

# 调用类方法
Foo.class_func()

# 调用静态方法
Foo.static_func()
  • The same point: For all methods, they belong to the class, so only one copy is saved in the memory
  • Differences: The method caller is different, and the parameters automatically passed in when calling the method are different.

Guess you like

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