classmethod、staticclassmethod内置装饰器函数

本文深入探讨了Python中类方法和静态方法的概念与使用场景。解析了如何使用@classmethod和@staticmethod装饰器来定义这两种方法,以及它们与实例方法的区别。通过具体案例,展示了类方法如何直接通过类名调用并修改类属性,而静态方法则适用于那些既不依赖对象状态也不依赖类状态的函数。
# method 英文是方法的意思

# classmethod   类方法
    # 当一个类中的方法中只涉及操作类的静态属性时,此时在逻辑上,我们想要直接通过类名就可以调用这个方法去修改类的静态属性,此时可以用这个内置装饰器函数
# staticmethod  静态方法

# 类的方法 classmethod
class Goods:
    discount = 0.5  # 折扣
    def __init__(self, name, price):
        self.name = name
        self.__price = price
    @property
    def price(self):
        return self.__price * Goods.discount

    def change_discount(self, newdiscount):  # 修改折扣
        Goods.discount = newdiscount

apple = Goods('苹果', 5)
print(apple.price)  # 2.5
apple.change_discount(2)    # 这么操作可以修改折扣,但是概念上无法理解,因为折扣修改的是整个超市的折扣,但这里居然用苹果的方法修改了类的折扣,是不合理的
print(Goods.discount)

class Goods:
    discount = 0.5  # 折扣
    def __init__(self, name, price):
        self.name = name
        self.__price = price
    @property
    def price(self):
        return self.__price * Goods.discount

    @classmethod    # 被此装饰器修饰的方法,也可以直接被类名调用了 cls代表类,像self(代表对象)
    def change_discount(cls, newdiscount):  # 修改折扣
        cls.discount = newdiscount

apple = Goods('苹果', 5)
print(apple.price)
Goods.change_discount(0.2)  # 此时就可以直接通过类名去调用方法,从而修改整个类的折扣了
print(apple.price)  # 1.0


# 类的静态方法 staticmethod
    # 在完全面向对象编程中,如果一个方法既和对象没有关系,又和类没有关系,那么就用staticmethod将这个方法变成一个静态方法
class Login:
    def __init__(self, name, password):
        self.name = name
        self.pwd = password
    def login(self):
        pass

    @staticmethod   # 被装饰的方法变为静态方法,既和对象没有关系,又和类没有关系,n
    def get_usr_pwd():
        usr = input('用户名')
        pwd = input('密码')
        Login(usr, pwd)


Login.get_usr_pwd() # 在完全面向对象编程中,如果一个方法既和对象没有关系,又和类没有关系,那么就用staticmethod将这个方法变成一个静态方法,可以直接这样调用



# 类方法和静态方法,都是类调用的
# 对象也是可以调用类方法和静态方法的,但不应该这么用

 

转载于:https://www.cnblogs.com/whylinux/p/9739473.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值