OOP跟我來
世界一切 歸于塵土
all is object
兩大殺手锏:對象 類
三大武器:封裝;繼承;多態
#!/usrself=Nonepython # -*- coding: utf-8 -*- # @File : people.py # @Author: wmy # @Date : 2018/1/21 class Person: aera = '地球' def __init__(self,name,age): self.name = name self.age = age def display_info(self): print(" -->%s已經%d歲,"%(self.name,self.age)) print("現住在%s..."%self.aera) p1 = Person('zhangsan',20) p1.display_info()
以上給出了一個簡單的類,其中p1為實例對象。
添加屬性:
p1.sex = 'male'
打印結果如下:
-->zhangsan已經20歲, 現住在地球... male
python很容易對類的屬性進行操作。
現在構造第二個對象:
p2 = Person('張天',40) p2.display_info()
輸出結果如下:
-->張天已經40歲, 現住在地球...
公共類變量:節省存儲空間
繼承如下
class Teacher(Person): def __init__(self,name,age,school): Person.__init__(self,name,age) self.school = school def display_info(self): Person.display_info(self) print('%s在%s學校任職'%(self.name,self.school))
通過類似公共接口的父類info函數,實現多態。這是Java不能如此簡單實現的。
class Person: aera = '地球' def __init__(self,name,age): self.name = name self.age = age def display_info(self): print(" -->%s已經%d歲,"%(self.name,self.age)) print("現住在%s..."%self.aera) @staticmethod def info(obj): obj.display_info() class Teacher(Person): def __init__(self,name,age,school): Person.__init__(self,name,age) self.school = school def display_info(self): Person.display_info(self) print('%s在%s學校任職'%(self.name,self.school)) class Doctor(Person): def __init__(self,name,age,medicine): Person.__init__(self,name,age) self.medicine = medicine def display_info(self): Person.display_info(self) print('%s在%s醫院任職'%(self.name,self.medicine)) t = Teacher('馬玉',20,'第二中學') d = Doctor('趙慎',34,'華西醫院') t.display_info() d.display_info() print('-------------------------') p = Person('福清',40) p.info(t) p.info(d)
結果如下:
-->張丹已經20歲, 現住在地球... 張丹在第二中學學校任職 -->撲打已經34歲, 現住在地球... 撲打在華西醫院醫院任職 ------------------------- -->張丹已經20歲, 現住在地球... 張丹在第二中學學校任職 -->撲打已經34歲, 現住在地球... 撲打在華西醫院醫院任職
小編帶領大家學習了一下Python,這種語言面向編程相對Java和C++來說。簡單許多喲!
浙公網安備 33010602011771號