#-*- coding:UTF-8 -*-
class C(object):
@staticmethod
def f():
print("runoob")
C.f() #静态方法无序实例化
cobj=C()
cobj.f()#也可以实例化后调用
应用场景:编写类时需要采用很多不同的方式类创建实例,而我们只有一个_init_函数,此时静态方法就派上用场了
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
@staticmethod
def now():
t=time.localtime()
return Date(t.tm_year,t.tm_mon,t.tm_mday)
@staticmethod
def 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()
类方法是给类用的,类在使用时会将类本身作为参数传给类方法的第一个参数,Python为我们内置了函数classmethod来把类中的函数定义成类方法。
import time
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
@calssmethod
def now(cls):
t=time.localtime()
return cls(t.tm_year,t.tm_mon,t.tm_mday)
class EuroDate(Date):
def __str__(self):#__xx__ 此种写法为Python内建属性方法,最好不要在外部调用
return "year:%s month:%s day:%s" % (self.year,self.month,self.day)
e=EuroDate.now()
print e