關於類方法和靜態方法
阿新 • • 發佈:2018-12-22
class Person(object): #私有類屬性 __type = "黃種人" def __init__(self): #例項屬性,都是在__init__方法裡! self.name = "小紅" #定義一個例項方法(接收self的就是例項方法,因為self就表示例項本身!) def show(self): print("我是例項方法") #用關鍵字classmethod修飾的方法就是類方法 @classmethod def show_msg(cls): print(cls) print("我是類方法!") print(cls.__type) #類方法的使用場景(在類的方法裡面可以獲取或修改類屬性!) @classmethod #修改類屬性 def set_type(cls,type): cls.__type = type #獲取類屬性 @classmethod def get_type(cls): return cls.__type #用關鍵字staticmethod修飾的方法就是靜態方法 #所謂靜態,就是和當前的類和例項沒有任何關係 #一般情況靜態方法會使用到當前類的邏輯,節省記憶體 @staticmethod def show_static():#不傳任何引數 print("我是靜態方法") #建立一個例項,利用例項呼叫(例項方法,類方法,靜態方法) p =Person() p.show() p.show_msg() p.show_static() print() #使用類名呼叫物件方法(需要傳入物件) Person.show(p) #使用類名呼叫類方法 Person.show_msg() #使用類名呼叫靜態方法 Person.show_static() #擴充套件 #使用例項呼叫類方法修改類屬性值 p.set_type("黑種人") #這裡的p是Person類的一個例項,所以就代表Person類了 res = p.get_type() #檢視類屬性修改成功沒有 print(res)
輸出結果:
最後用例項呼叫類方法,成功的把類的私有屬性修改為“黑種人”,並列印。