1. 程式人生 > >類以及類的繼承

類以及類的繼承

ont eating xiaomi pan 之前 money people 父類 會有

1、創建類
class People:
def __init__(self,name,age):
self.name = name
self.age = age
def eat(self):
print("%s is eating food" % self.age)
def sing(self):
print("%s is singing a song" % self.name)
def nianling(self):
print("%s is %s years old" % (self.name,self.age))

2、類的實例化(即建立一個具體對象)
p1 = People("xiaoming",22) 單獨有這行啥也不顯示,而要配合下邊的語句才能實現

p1.nianling() 顯示:xiaoming is 22 years old

3、類的繼承
class Man(People): #People就表示繼承了上邊的類
def __init__(self,name,age,money): #對父類的初始化添加新功能 money
People.__init__(self,name,age) #繼承調用上邊的父類,避免輸入重復代碼
self.money = money
print("%s 一出生就有%s money %(self.name,self.money))

def sleep(self):
print("%s is sleeping" % self.name)
m1 = Man("xiaogang",22,100) 繼承之前的類,也就相當於是實例化了,所以每行都會有實現的結果
m1.sleep()
顯示:
xiaogang 一出生就有 100 dollers
xiaogang is sleeping



 

類以及類的繼承