class student: __name = "xiaoming" __sex = "man" __age = "15" def getName(self): return self.__name def setName(self,name): self.__name = name s = student() s.setName("xiaohong") print(s.getName())
能夠把它當作C++中類裏面的this指針同樣理解,就是對象自身的意思,在用某個對象調用該方法時,就將該對象做爲第一個參數傳遞給self。this
init()構造方法,建立對象.net
class student: def __init__(self): self.__name = "xiaoming" self.__sex = "man" self.__age = 15 def getName(self): return self.__name def setName(self,name): self.__name = name s = student() s.setName("xiaohong") print(s.getName())
del()析構方法指針
刪除實例化的對象code
class friend(): def __init__(self): self.__name = "putao" self.__location = "jiapali" def __del__(self): print("刪除對象") def getName(self): return __name__ putao = friend() del putao print(putao.getName())
class 子類(父類)對象
class people: name = 'human' def sleep(self): print(self.name, "sleep") class chinese(people): def eat(self): print(self.name, "eat") c = chinese() c.sleep() #human sleep c.eat() #human eat c.name = "xiaoMing" c.sleep() #xiaoMing sleep c.eat() #xiaoMing eat
class 子類(父類A,父類B)繼承
若是有父類有相同方法,A優先調用get
子類覆寫父類方法,子類方法優先調用it
類方法傳入類自己做爲參數clsio
使用註解@classmethodclass
類方法能夠動態配置
class Color(): __color = (0,0,0) @classmethod def getColor(cls): if cls.__name__ == 'Red': cls.__color = (255,0,0) elif cls.__name__ == 'Green': cls.__color = (0,255,0) return cls.__color class Red(Color): pass class Green(Color): pass print(Red.getColor()) # (255, 0, 0) print(Green.getColor()) # (0, 255, 0)
@staticmethod 註解在類的靜態方法上, 靜態方法只能用類對象訪問