The difference between python class methods and static methods is explained in detail

instance method

1. It can only be called through the object (the first parameter self: represents the object itself)
2. Applicable scenario: If you want to use the properties or methods of the object inside the method, you must define it as an object method

class method

1. First use @classmethod declaration
2. (The first parameter cls: represents the class itself)
3. It can be called by class or by object
4. Applicable scenarios: only class attributes or class methods are used inside the method (no need using object properties and methods), suitable for defining as class methods

static method

1. Use @staticmethod declaration first
. 2. It can be called by class or by object.
3. Applicable scenario: inside the method (neither need to use class properties and class methods nor object properties and methods), it is suitable to be defined as static method method

class Demo:
    def func(self):
        print("---实例方法---")

    @classmethod
    def work(cls):
        print("---类方法---")

    @staticmethod
    def work1():
        print("---静态方法---")


d = Demo()
d.func()
d.work()
d.work1()
Demo.func()  # 不能通过类去调用

Well, the above is all the content of this article, I hope it will be helpful to you, and I hope you will give a lot of support to Code Farmer's House . Your support is the driving force for my creation! I wish you all a happy life!    

Guess you like

Origin blog.csdn.net/wuxiaopengnihao1/article/details/127921065