一,繼承
class person(object):
def __init__(self, name, ***):
self.name = name
self.*** = ***
def print_title(self):
if self.*** == "male":
print("man")
elif self.*** == "female":
print("woman")
class child(person): # child 繼承 person
pass
lice = child("lice", "female")
peter = person("peter", "male")
print(lice.name, lice.***, peter.name, peter.***) # 子類繼承父類方法及屬性
二,多型,重寫父類方法
class person(object):
def __init__(self, name, ***):
self.name = name
self.*** = ***
def print_title(self):
if self.*** == "male":
print("man")
elif self.*** == "female":
print("woman")
class child(person): # child 繼承 person
三,子類重寫建構函式
class person(object):
def __init__(self,name,***):
self.name = name
self.*** = ***
class child(person): # child 繼承 person
def __init__(self,name,***,mother,father):
self.name = name
self.*** = ***
self.mother = mother
self.father = father
lice = child("lice","female","haly","peter")
print(lice.name,lice.***,lice.mother,lice.father)
四,父類建構函式包含很多屬性,子類僅需新增1、2個,會有不少冗餘的**,這邊,子類可對父類的構造方法進行呼叫
class person(object):
def __init__(self,name,***):
self.name = name
self.*** = ***
class child(person): # child 繼承 person
def __init__(self,name,***,mother,father):
person.__init__(self,name,***) # 子類對父類的構造方法的呼叫
self.mother = mother
self.father = father
# self.name='haha'
lice = child("lice","female","haly","peter")
print(lice.name,lice.***,lice.mother,lice.father)
五,多重繼承,新建乙個類 baby 繼承 child , 可繼承父類及父類上層類的屬性及方法,優先使用層類近的方法,
#coding:utf-8
class person(object):
def __init__(self, name, ***):
self.name = name
self.*** = ***
def print_title(self):
if self.*** == "male":
print("man")
elif self.*** == "female":
print("woman")
class child(person):
pass
class baby(child):
pass
lice = baby("lice", "female") # 繼承上上層父類的屬性
print(lice.name, lice.***)
lice.print_title() # 可使用上上層父類的方法
print('***************===')
class child(person):
def print_title(self):
if self.*** == "male":
print("boy")
elif self.*** == "female":
print("girl")
class baby(child):
pass
lice2 = baby("lice2", "female")
print(lice2.name, lice2.***)
lice2.print_title() # 優先使用上層類的方法
python類的繼承與多型
定義乙個類 class animal object defrun self print animal is runnning 繼承此類 class dog animal pass例項化 dog.run animal is runnning 以上 母類擁有乙個方法 此方法會繼承到子類,故子類也可以執行...
python類的繼承與多型
繼承 class 類名 父類名 子類繼承父類,執行初始化 init 時,子類屬性要把 父類名.init 方法 屬性 全部寫上 在給物件賦值 如果子類物件使用父類的方法屬性 1可以在子類方法中,寫上父類的方法及屬性 父類 init 方法 屬性 經典類寫法 2或者用super呼叫父類方法,super 或...
python 類的繼承與多型
類的繼承 class anmial object anmial 類繼承object def init self,self.def eat self print anmial is eating def run self print running class cat anmial cat類繼承anm...