Python繼承機制

被繼承的類稱爲基類、父類或超類;繼承者稱爲子類,一個子類可以繼承它的父類的任何屬性和方法。舉個例子:

# 類名大寫,方法名小寫,約定俗稱
class Parent:
	def hello(self):
		print("using parent's class...")
	
class Child(Parent):
	pass

p = Parent()
p.hello()
using parent's class...

c = Child()
c.hello()
using parent's class...
  • 子類中定義與父類同名的方法或屬性,則會自動覆蓋父類對應的方法

繼承

例子:

import random as r
# 父類
Class Fish:
	def __init__(self):
		self.x = r.randint(0, 10)
		self.y - r.randint(0, 10)
	def move(self):
		self.x -= 1
		print("my seat: ", self.x, self.y)
		
# 子類
Class Shark(Fish):
	def __init__(self):
		self.hungry = True
	def eat(self):
		if self.hungry:
			print("i want eat...")
			self.hungry = False
		else:
			print("I am full, don't eat...")
shark = Shark()
shark.move()
Trackback (most recent call last):
   AttributeError: 'Shark' object has no attribute 'x'
# 原因:在shark類中,重寫了__init__()方法,但是新的__init__()方法裏沒有初始化父類的屬性(這裏是x,y),因此調用move方法就會出錯。結局方法:使用super函數
class Shark(Fish):
	def __init__(self):
		super().__init__()
		...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章