【python38--面向對象繼承】
一、繼承
1、語法:class DerivedClassName(BaseClassName):子類繼承父類
>>> class Parent: def hello(self): print(‘正在調用父類的方法。。。‘) >>> class Child(Parent): pass >>> p = Parent() >>> p.hello() 正在調用父類的方法。。。 >>> c = Child() >>> c.hello() 正在調用父類的方法。。。>>> #子類Child繼承了父類Parent,所以子類可以調用父類的方法c.hello()
2、如果子類中定義的方法和屬性和父類的屬性和方法名字一樣,則會自動覆蓋父類對應的方法和屬性
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(‘我的位置‘,self.x,self.y)
class Goldfish(Fish):
pass
class Carp(Fish):
pass
class Salmon(Fish):
pass
class Shark(Fish):
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print(‘吃貨的夢想就是天天吃肉!‘)
self.hungry = False
else:
print(‘吃撐了!‘)
>>> fish = Fish()
>>> fish.move()
我的位置 4 7
>>> goldfish = Goldfish()
>>> goldfish.move()
我的位置 6 5
>>> carp = Carp()
>>> carp.move()
我的位置 7 6
>>> salmon = Salmon()
>>> salmon.move()
我的位置 -1 10
>>> shark = Shark()
>>> shark.move()
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
shark.move()
File "/Users/yixia/Desktop/fish.py", line 9, in move
self.x -=1
AttributeError: ‘Shark‘ object has no attribute ‘x‘
---報錯的原因:AttributeError: ‘Shark‘ object has no attribute ‘x‘ :Shark沒有x的屬性,shark繼承了Fish,為什麽會沒有x的屬性呢
原因:Shark重寫了__init__的方法,就會覆蓋父類Fish的__init__()方法中的x屬性,即:子類定義類一個和父類相同名稱的方法,則會覆蓋父類的方法和屬性
改正的代碼:
兩種方法:1,調用未綁定的父類方法 2、使用super()函數
實現的代碼如下:
第一種:
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(‘我的位置‘,self.x,self.y)
class Goldfish(Fish):
pass
class Carp(Fish):
pass
class Salmon(Fish):
pass
class Shark(Fish):
def __init__(self):
Fish.__init__(self) #父類名稱調用__init__()函數
self.hungry = True
def eat(self):
if self.hungry:
print(‘吃貨的夢想就是天天吃肉!‘)
self.hungry = False
else:
print(‘吃撐了!‘)
>>> shark = Shark()
>>> shark.move()
我的位置 1 8
>>>
第二種:
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(‘我的位置‘,self.x,self.y)
class Goldfish(Fish):
pass
class Carp(Fish):
pass
class Salmon(Fish):
pass
class Shark(Fish):
def __init__(self):
super().__init__() #采用super()函數
self.hungry = True
def eat(self):
if self.hungry:
print(‘吃貨的夢想就是天天吃肉!‘)
self.hungry = False
else:
print(‘吃撐了!‘)
>>> shark = Shark()
>>> shark.move()
我的位置 -1 6
【python38--面向對象繼承】