靜態函數與類方法
靜態函數其實和類的方法沒什麼關係,它只是恰好定義在類的內部而已,所以這裏我用函數(function) 來形容它。它可以沒有參數:
class Person:
@staticmethod # 用 staticmethod 這個修飾器來表明函數是靜態的
def sayHello():
print('Hello')
Person.sayHello() # 輸出 'Hello`
靜態函數的調用方式是類名加上函數名。類方法的調用方式也是這樣,唯一的不同是需要用 @staticmethod
修飾器,而且方法的第一個參數必須是類:
class Person:
@classmethod # 用 classmethod 這個修飾器來表明這是一個類方法
def sayHi(cls):
print('Hi: ' + cls.__name__)
Person.sayHi() # 輸出 'Hi: Person`
# 在 module1.py 文件中:
def global():
pass
class Util:
@staticmethod
def helper():
pass
# 在 module2.py 文件中:
import module1
module1.global() # 調用全局函數
module1.Util.helper() # 調用靜態函數
class Data_test2(object):
day=0
month=0
year=0
def __init__(self,year=0,month=0,day=0):
self.day=day
self.month=month
self.year=year
@classmethod
def get_date(cls, string_date):
#這裏第一個參數是cls, 表示調用當前的類名
year,month,day=map(int,string_date.split('-'))
date1=cls(year,month,day)
#返回的是一個初始化後的類
return date1
def out_date(self):
print "year :"
print self.year
print "month :"
print self.month
print "day :"
print self.day
參考資料