前言
python类中方法有三种:静态方法(staticmethod)、类方法(classmethod)、实列方法。
本文主要介绍下静态方法(staticmethod)和类方法(classmethod)。
使用(fake)
class TestFuc(object):
def instance_fuc(self, x):
print('instance_fuc(%s,%s)' % (self, x))
@classmethod
def class_fuc(cls,x):
print('class_fuc(%s,%s)' % (cls,x))
@staticmethod
def static_fuc(x):
print('static_fuc(%s)' % x)
test_fuc = TestFuc()
# 实例方法
test_fuc.instance_fuc(1)
# 类方法
test_fuc.class_fuc(1)
TestFuc.class_fuc(1)
# 静态方法
test_fuc.static_fuc(1)
TestFuc.static_fuc(1)
应用
脱离了实际的应用场景,谈使用就是是耍流氓。上文介绍的"使用"仅仅展示如何定义(进入)和伪使用,真正的场景不会这样用的。
静态方法(staticmethod)和类方法(classmethod)并不常用。我喜欢在stackoverflow:What is the advantage of using static methods in Python?的一句话:"So they aren't useful for day-to-day methods"。尽管如此,我们依然要学习,并熟悉使用(原因:语言特性的完整、特殊场景的使用)。
目前,我看到网上介绍比较多应用用它们作为构造函数。
# staticmethod实现
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
@staticmethod
def now(): #用Date.now()的形式去产生实例,该实例用的是当前时间
t=time.localtime() #获取结构化的时间格式
return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建实例并且返回
@staticmethod
def tomorrow():#用Date.tomorrow()的形式去产生实例,该实例用的是明天的时间
t=time.localtime(time.time()+86400)
return Date(t.tm_year,t.tm_mon,t.tm_mday)
a=Date('1987',11,27) #自己定义时间
b=Date.now() #采用当前时间
c=Date.tomorrow() #采用明天的时间
print(a.year,a.month,a.day)
print(b.year,b.month,b.day)
print(c.year,c.month,c.day)
继承类中的区别
- 子类的实例继承了父类的static_method静态方法,调用该方法,还是调用的父类的方法和类属性。
- 子类的实例继承了父类的class_method类方法,调用该方法,调用的是子类的方法和子类的类属性。
class Foo(object): X = 1 Y = 2 @staticmethod def averag(*mixes): return sum(mixes) / 1 @staticmethod def static_method(): return Foo.averag(Foo.X, Foo.Y) @classmethod def class_method(cls): return cls.averag(cls.X, cls.Y) class Son(Foo): X = 3 Y = 5 @staticmethod def averag(*mixes): return sum(mixes) / 2 p = Son() print(p.static_method()) print(p.class_method())