Python中的实例方法、静态方法和类方法有什么区别?

  • 实例方法:接受self参数,并且与类的特定实例相关。

  • 静态方法:使用装饰器 @staticmethod,与特定实例无关,并且是自包含的(不能修改类或实例的属性)。

  • 类方法:接受cls参数,并且可以修改类本身。

我们将通过一个虚构的CoffeeShop类来说明它们之间的区别。

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

制作不易,点赞鼓励哈

猜你喜欢

转载自blog.csdn.net/weixin_42464956/article/details/107487196
今日推荐