溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python中繼承父類方法

發(fā)布時間:2020-07-20 10:12:03 來源:億速云 閱讀:230 作者:清晨 欄目:編程語言

這篇文章主要介紹python中繼承父類方法,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

繼承父類方法

子類可以直接調(diào)用父類的方法

class Person():
	def __init__(self):
		pass			
	def hello(self):
		print 'hello'		
class Student(Person):
	def __init__(self):
		pass				
s = Student()
s.hello()				# hello

繼承父類屬性

這里要注意, 如果要繼承父類的屬性, 一定要在子類的構(gòu)造函數(shù)里調(diào)用父類的構(gòu)造函數(shù), 否則會報錯無法訪問, 因為父類的構(gòu)造函數(shù)沒有被調(diào)用, 構(gòu)造函數(shù)中的屬性自然也就沒有被聲明

這時如果調(diào)用父類的屬性則會報錯, 報錯內(nèi)容為Student實例沒有name屬性

# coding=utf-8

class Person():
	def __init__(self):
		self.name = '小明'
		self.age = 18	
		print('Person class init completed')		
	def hello(self):
		print 'hello'
class Student(Person):
	def __init__(self):
		print ('Student class init completed')		
s = Student()
print s.name

# Student class init completed
# Traceback (most recent call last):
#   File ".\classDemo.py", line 23, in <module>
#     print s.name
# AttributeError: Student instance has no attribute 'name'

下面是子類在構(gòu)造函數(shù)中調(diào)用父類構(gòu)造函數(shù)的情況, 子類實例可以訪問父類屬性

# coding=utf-8

class Person():
	def __init__(self):
		self.name = u'小明'
		self.age = 18		
		print('Person class init completed')			
	def hello(self):
		print 'hello'		
class Student(Person):
	def __init__(self):
		Person.__init__(self)		
		print ('Student class init completed')				
s = Student()
print s.name

# Person class init completed
# Student class init completed
# 小明

方法重寫

有時候父類提供的方法不能滿足需求時, 可以在子類中重寫父類的方法

在父類Person中, 構(gòu)造函數(shù)只定義了name和age兩個屬性, print_into()函數(shù)也只打印了name, age這兩個屬性

在子類Student中, 多了一個school屬性, 顯然父類的提供方法功能不夠了, 這時候, 子類就需要對父類的方法進行重寫, 擴充父類的功能

# coding=utf-8

class Person(object):
	def __init__(self, name, age):
		self.name = name
		self.age = age			
	def print_info(self):
		print 'name: ', self.name
		print 'age: ', self.age		
class Student(Person):
	def __init__(self, name, age, school):
		Person.__init__(self, name, age)		
		self.school = school		
	def print_info(self):
		super(Student, self).print_info()
        # python3 中可直接使用super()
        # Python2 一般為super(class, self), 且class要為新類
        # 新類就是由內(nèi)置類型派生出來的類
		print 'school: ', self.school				
s = Student(u'小明', 18, u'家里蹲大學')
s.print_info()
	
# name:  小明
# age:  18
# school:  家里蹲大學

以上是python中繼承父類方法的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI