1.@classmethod 的作用
被装饰的方法会成为一个类方法
1.在方法中仍然可以引用静态变量
2.可以不用实例化对象,就可以调用一个类方法
在定义了一个方法默认传入self的时候,但是这个self没有被使用的时候
并且你在这个方法里用到了当前的类名,或者你准备使用这个类的内存空间中的名字的时候
就可以使用@classmethod方法了
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 =Date(struct_t.tm_year,struct_t.tm_mon,struct_t.tm_mday) # struct_t.tm_year,struct_t.tm_mon,struct_t.tm_mday # 分别作了参数传入了 self.yearself.month,self.day return date 今天的日期 = Date .today() print(今天的日期.year)
2.@staticmethod 被装饰的对象会成为一个静态方法
lass User: pass @staticmethod def func():# 因为被@staticmethod装饰了所以可以不用传递变量 print('登录') User.func()