classmethodstaticclassmethod内置装饰器函数(代码片段)

whylinux whylinux     2023-01-05     752

关键词:

# 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将这个方法变成一个静态方法,可以直接这样调用



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