What is the difference between instance method, static method and class method in Python?

  • Instance method: accepts the self parameter and is related to a specific instance of the class.

  • Static method: Use the decorator @staticmethod, which has nothing to do with a specific instance and is self-contained (you cannot modify the properties of the class or instance).

  • Class method: accept cls parameters, and can modify the class itself.

We will illustrate the difference between them through a fictitious CoffeeShop class.

class CoffeeShop:
     #类有一个属性specialty,默认值设为“espresso”
    specialty = 'espresso'

    def __init__(self, coffee_price):
        self.coffee_price = coffee_price

    # instance method  实例方法
    def make_coffee(self):
        print(f'Making {self.specialty} for ${self.coffee_price}')

    # static method     静态方法
    @staticmethod  
    def check_weather():
        print('Its sunny')  

   # class method 类方法
    @classmethod
    def change_specialty(cls, specialty):
        cls.specialty = specialty
        print(f'Specialty changed to {specialty}')
coffee_shop = CoffeeShop(5)
coffee_shop.make_coffee()      
 #=> Making espresso for $5
coffee_shop.check_weather()
 #=> Its sunny
coffee_shop.change_specialty('drip coffee') 
#=> Specialty changed to drip coffee
coffee_shop.make_coffee()
#=> Making drip coffee for $5

It is not easy to make, please like and encourage

Guess you like

Origin blog.csdn.net/weixin_42464956/article/details/107487196