在python中,各種方法的定義如下所示:
class MyClass(object):
#在類中定義普通方法,在定義普通方法的時候,必須添加self def foo(self,x): print "this is a method %s %s" % (self,x)
#在類中定義靜態方法,在定義靜態方法的時候,不需要傳遞任何類的東西 @staticmethod def static_method(x): print "this is a static method: %s " % x
#在類中定義類方法,在定義類方法的時候,需要傳遞參數cls @classmethod def class_method(cls,x): print "this is a class method: %s %s" %(cls,x)
1、 在定義普通方法的時候,需要的參數是self,也就是把類的實例作為參數傳遞給方法,如果在不寫self的時候,會發現報錯TypeError錯誤,表示傳遞參數多了,其實也就是在調用類方法的時候,將實例作為參數傳遞了。
在使用普通方法的時候,必須是使用實例來調用方法,不能使用類來調用方法,沒有實例,那么方法將無法調用。
2、 在定義靜態方法的時候,和模塊中的方法沒有什么不同,最大的不同就在於靜態方法在類的命名空間之中,並且在聲明靜態方法的時候,使用的標記為@staticmethod,表示為靜態方法,在調用靜態方法的時候,可以使用類名或者是實例名來進行調用,一般使用類名來進行調用
靜態方法主要是用來放一些方法,方法的邏輯屬於類,但是又和類本身沒有交互,從而形成了靜態方法,主要是讓靜態方法放在此類的名稱空間之內,從而能夠更加有組織性。
3、 在定義類方法的時候,傳遞的參數為cls,表示為類,此寫法也可以變,但是一般寫為cls。類的方法調用可以使用類,也可以使用實例,一般的情況下是使用類。
4、 self表示為類型為類的object,而cls表示為類也就是class
5、在繼承的時候,靜態方法和類方法都會被子類繼承。在進行重載類中的普通方法的時候,只要 寫上相同的名字即可進行重載。
6、 在重載調用父類方法的時候,最好是使用super來進行調用父類的方法。
靜態方法主要用來存放邏輯性的代碼,基本在靜態方法中,不會涉及到類的方法和類的參數。
類方法是在傳遞參數的時候,傳遞的是類的參數,參數是必須在cls中進行隱身穿
class Date(object): day = 0 month = 0 year = 0 #define the init parameter def __init__(self,day=0,month=0,year=0): self.day = day self.month = month self.year = year #this is for the class method ,and the method is use parameter #this must use the parameter of the self,this is for the object def printf(self): print "the time is %s %s %s " %(self.day,self.month,self.year) #this is define a classmethod,and the praemter have a cls,and can use the cls to create a class #cls is passed of the class,then can initiate the object @classmethod def from_string(cls,date_as_string): day,month,year = map(int,date_as_string.split("-")) date1 = cls(day,month,year) date1.printf() #this is the static method,and thre is do something to manage the logic,not the class or object @staticmethod def is_date_valid(date_as_string): day,month,year = map(int,date_as_string.split("-")) return day <= 31 and month <= 12 and year <= 3999