通过加上@ classmethod 将函数属性变为类方法 调用方式变为类名加上函数名 从而不需要经过实例化 例如:
1 class Room: 2 def __init__(self, name, owner, width, length, heigh): 3 self.name = name 4 self.owner = owner 5 self.width = width 6 self.length = length 7 self.heigh = heigh 8 9 @property # 函数属性变为数据属性,调用方式改变 10 def cal_area(self): 11 # print('%s 住的 %s 总面积是%s' % (self.owner, self.name, self.width * self.length)) 12 return self.width * self.length 13 14 @property 15 def cal_total(self): 16 return self.width * self.length * self.heigh 17 18 @classmethod # 表示这是类方法,默认传递类本身。通过类名.函数名 19 def tell_info(cls): 20 print(cls) 21 print('你好,这是类方法') 22 23 24 Room.tell_info() 25 输出: 26 <class '__main__.Room'> 27 你好,这是类方法
用处,跟实例没有关系,只跟类有关系的
类方法只能访问类属性
实例也可以调用类方法 此时将实例传进形参cls