静态方法和类方法
静态方法(@staticmethod)、类方法(@classmethod),可被类或类的实例对象调用。
class 中的方法
实例方法,第一个参数必须要默认传实例对象,一般习惯用self。
静态方法,参数没有要求。
类方法,第一个参数必须要默认传类,一般习惯用cls。
二者区别
感觉唯一区别就是类方法第一个参数默认是类本身,当有子类继承时,传入的是子类对象
静态方法节约内存,可读性相对好一点
如果不需要获取访问类信息和属性用静态方法
例子:
import time
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@staticmethod # 静态方法
def static_now():
t = time.localtime()
return Date(t.tm_year, t.tm_mon, t.tm_mday)
@classmethod # 类方法
def class_now(cls):
t = time.localtime()
return cls(t.tm_year, t.tm_mon, t.tm_mday)
class EuroDate(Date):
def __str__(self):
return 'year:%s month:%s day:%s' % (self.year, self.month, self.day)
if __name__ == '__main__':
e = EuroDate.static_now()
print(e)
e = EuroDate.class_now()
print(e)
输出结果:
<Date object at 0x10e5a7be0>
year:2019 month:1 day:25