python基础 day27 装饰器函数classmethod、staticmethod

一、classmethod装饰器函数

class Goods:
    __discount = 0.8
    def __init__(self):
        self.__price = 5
        self.price = self.__price * self.__discount
    @classmethod  # 把一个对象绑定的方法,修改成一个类方法
    def change_discount(cls, new_discount):
        cls.__discount = new_discount
apple = Goods()
print(apple.price)

# 修改折扣
# @classmethod  # 把一个对象绑定的方法,修改成一个类方法
# 在方法中仍然可以引用类中的静态变量
# 可以不用实例化对象,就直接用类名在外部调用这个方法
Goods.change_discount(0.6)  # 可以通过类名调用类方法
apple2 = Goods()
print(apple2.price)
  • classmethod 使用实例
import time
class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day
    @classmethod
    def today(cls):
        current_time = time.localtime()
        date = cls(current_time.tm_year, current_time.tm_mon, current_time.tm_mday)
        return date
today = Date.today()
print(today.year)
print(today.month)
print(today.day)

二、staticmethod装饰器函数

# @staticmethod 被装饰的方法会成为一个静态方法
# 使用场景:在函数的内部既不会用到self变量,也不会用到cls类
class User:
    pass

    @staticmethod
    def login():  # 本身是一个普通的函数,被挪到类的内部执行,那么直接给这个函数添加@staticmethod装饰器就可以了
        print('登录的逻辑')
    
User.login()

三、__call__方法和__len__方法

# 对象() 能不能运行就是callable判断的事情

class A:
    def __call__(self, *args, **kwargs):
        print('abc')

obj = A()
print(callable(obj))
obj()  # abc'''



'''# __len__ 方法
class Cls:
    def __init__(self, name):
        self.name = name
        self.student = []
    def __len__(self):
        return len(self.student)

jason857 = Cls("jason857")

jason857.student.append('jason')
jason857.student.append('dog')
print(len(jason857))'''
原文地址:https://www.cnblogs.com/west-yang/p/13221794.html