classmethod和staticmethod装饰器

2023-07-12,,

"""
两个装饰
@classmethod 把一个对象绑定的方法,修改成为一个类方法
1.在方法中仍然可以引用类中的静态变量
2.可以不用实例化对象,就直接使用类名在外部调用这个方法
什么时候用?
1.定义了一个方法,默认传参self,但这个self没有被使用
2.并且你在这个方法里用到了当前的类名,或者你准备使用这个类的内存空间中的名字的时候 @staticmethod
静态方法 """ 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) Goods.change_discount(0.6)
apple1 = Goods()
print(apple1.price) # 在自己类里面实例化
import time
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def today(cls):
struct_t = time.localtime()
date = cls(struct_t.tm_year, struct_t.tm_mon, struct_t.tm_mday)
return date
date = Date.today()
print(date.year)
print(date.month)
print(date.day) # @staticmethod 被装饰的方法会成为一个静态方法 class User:
pass @staticmethod
def login(): #本身是一个普通的函数,被移到类的内部执行,那么直接给这个函数添加@staticmethod就可以了
print("登录")
# 在函数内部既不会用到self,也不会用到cls时用 User.login()

classmethod和staticmethod装饰器的相关教程结束。

《classmethod和staticmethod装饰器.doc》

下载本文的Word格式文档,以方便收藏与打印。