python面向對象的三大特性:封裝、繼承、多態
- 封裝是指它能通過創建一個類,並將若干個屬性和方法包裝在這個類中,程序員只需創建這個類的一個對象便可以調用這些屬性和方法。
# 定義一個類
class Person():
def eat(self):
print("吃")
def sleep(self):
print("睡覺")
# 創建一個人的對象p,它可以調用Person類的方法
p = Person()
p.eat()
p.sleep()
- 繼承是對多個類而言的,比如B類繼承了A類之後,可以調用A類的所有公有屬性和公有方法。
class Person():
def eat(self):
print("吃")
def sleep(self):
print("睡覺")
# 創建Person的一個子類Doctor類
class Doctor(Person):
pass
# 創建一個Doctor類的對象d,它可以調用它的父類Person類的方法
d = Doctor()
d.eat()
d.sleep()
- 多態是在繼承的基礎上,同一個函數被不同的類調用之後有不同的效果。
class Person():
def __init__(self,name):
self.name = name
def eat(self):
print("%s 在吃飯" %(self.name))
def sleep(self):
print("睡覺")
# 創建Person的一個子類Doctor類
class Doctor(Person):
def __init__(self,name):
self.name = name
p = Person("小明")
p.eat() # 返回 “小明 在吃飯”
d = Doctor("小紅")
p.eat() # 返回 “小紅 在吃飯”
對象d調用了父類Person中的方法eat(),而使用的屬性name是在定義對象d是賦予的。