类的三大装饰器之classmethod

@classmethod: *****
类的对象绑定的方法都是默认传self参数的,但是当这个self在方法中不被使用时,
然后在方法中准备使用类的静态属性,就可以将该方法修改为类方法
在外部可以不用实例化对象直接通过类名调用类方法

class Goods(object):
    __discount = 0.8
    def __init__(self):
        self.__price = 5
        self.price = self.__price * self.__discount

    @classmethod  # 把一个对象绑定的方法修改成一个类方法
    def change_discount(cls, new_discount): # cls参数指代本类
        cls.__discount = new_discount


apple = Goods()
print(apple.price)

# 修改折扣为 0.6
Goods.change_discount(0.6)
# apple.change_discount(0.6)
apple2 = Goods()
print(apple2.price)


import time
class Date(object):
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    @classmethod
    def today(cls):
        struct = time.localtime()
        # now_day = time.strftime('%Y-%m-%d', time.localtime())
        date = cls(struct.tm_year, struct.tm_mon, struct.tm_mday)
        return date



date = Date.today() # 这个对象是由Date类的类方法中实例化后返回的
print(date.year, date.month, date.day)
原文地址:https://www.cnblogs.com/GOD-L/p/13541051.html