python类的继承及重写父类方法
写python有一年多了,平日使用Python解决一些问题,调一些接口,用一些框架,虽然不影响都可以写,但一直没有好好的花时间去理解Python概念性的东西。也许,这也是写了这么久一直不能有所进步的原因,从今天起,来重新好好的学习一下Python的相关概念。
1.类的继承,我们先来写两个类,他们之间为包含关系。类A为(Tree)树,类B为(Apple)苹果树,类C为(Pear)梨子树
class Tree:
def __init__(self,name,age):
self.name = name
self.age = age
def grow(self):
print("{} tree is growing...now it's {} years old".format(self.name,self.age))
def seed(self):
print("{} tree is seeding...".format(self.name))
class Apple(Tree):
"""docstring for ClassName"""
def __init__(self, name, age, color):
super().__init__(name,age)
self.color = color
def price(self):
print("One {} tree is 100 dollars".format(self.name))
class Pear(Tree):
"""docstring for ClassName"""
def __init__(self, name, age, color):
super().__init__(name,age)
self.color = color
def price(self):
print("One {} {} tree is 80 dollars".format(self.color,self.name))
def grow(self):
#重写父类的方法grow生长
print("it was {} years old,now it is {} years old".format(self.age,int(self.age)+1))
if __name__ == '__main__':
a = Apple('White Apple',8,'white')
a.grow()
a.seed()
a.price()
b = Pear('Pear',8,'red')
b.price()
b.grow()
>>>
#White Apple tree is growing...now it's 8 years old
#White Apple tree is seeding...
#One White Apple tree is 100 dollars
#One red Pear tree is 80 dollars
#it was 8 years old,now it is 9 years old
2.类Tree是各种树的总称,可理解为苹果树,梨子树等抽象后的上层概念。类Apple和类Pear都继承了类Tree,其中self.name
和self.age
是父类Tree的属性,self.color
是子类Apple和Pear的属性。通过继承,Apple和Pear可以直接使用父类的方法和属性。
3.父类方法的改写,可通过在子类中重写相同函数名的方式进行改写。
class Tree:
...
...
def grow(self):
print("{} tree is growing...now it's {} years old".format(self.name,self.age))
class Pear(Tree):
···
···
def grow(self):
#重写父类的方法grow生长
print("it was {} years old,now it is {} years old".format(self.age,int(self.age)+1))
4.super函数的用法
- python2和python3中的区别
python2 super(Tree,self).__init__(name,age)
python3 super().__init__(name,age)
在子类中使用super()函数,super()函数可以见到理解为代表父类Tree()。当需要在子类中调用父类的方法时,我们可以用super()来表示父类Tree()
···
···
class orange(Tree):
def grow(self):
#调用父类Tree的方法grow
super().grow()
#直接调用Tree类的方法
Tree('Apple','16').grow()
#重写父类方法grow
print("{} tree has changed...".format(self.name))
orange('orange','15')
>>>
#orange tree is growing...now it's 15 years old
#Apple tree is growing...now it's 16 years old
#orange tree has changed...
- Python允许多重继承例如
class fruits(Apple,Tree)
的用法,多重继承容易出现父类方法多次调用的问题,可以通过super的使用来确保父类方法只被调用一次。python类的继承顺序是根据MRO,通过C3算法来计算的。我的理解当出现类方法的多次调用时,super会确保执行距离子类最近的所继承的父类的方法。对该问题感兴趣,可以深入了解砖石继承和super。总之,不是必须一般不推荐使用多重继承