社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
两个中有大量重复的代码,是否能够只写一次 ?抽象出一个更抽象的类,放公共代码
通过继承能够重用代码,方便代码的管理和修改
继承并不是复制变量空间,子类更新成员变量,但是父类的成员变量不会随之更新。
继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个Dog类型的对象派生自Animal类。
我们生活中的直系亲属之间的遗传类似于继承,如图
继承并不是复制变量空间,子类更新成员变量,但是父类的成员变量不会随之更新。
#继承并不是复制变量空间,子类更新成员变量,但是父类的成员变量不会随之更新。
class A(object):
name = 'a_name'
class B(A):
pass
print(A.name,B.name)
B.name = 'b_name'
print(A.name,B.name)#子类B更新成员变量,但是父类A的成员变量不会随之更新。
a_name a_name
a_name b_name
通过继承能够重用代码,方便代码的管理和修改
#通过继承能够重用代码,方便代码的管理和修改
#Define a class called Rectangle 定义一个长方形类
class Rectangle(object):
def __init__(self,length,width):
self.length = length
self.width = width
def get_area(self):
return self.length * self.width
#Compute the area of rectangle_a 计算长方形的面积
rectangle_a = Rectangle(20,30)
print(rectangle_a.get_area())
#Define another class named Square which is the subclass of Rectangle 定义Rectangle的子类Square
class Square(Rectangle):
pass
#Compute the area of square_b 计算正方形b的面积 正方形是特殊的矩形计算矩形面积的公式也适用于正方形,这显然节省了代码量
square_b = Square(20,20)
print(square_b.get_area())
600
400
多继承时的相同方法的继承顺序,相同方法的话从左到右依次检索
class Dog:
def specialty(self):
print('aaaaa')
class God:
def specialty(self):
print('God')
class God_Dog(Dog,God): #谁先继承就用谁,相同方法的话从左到右依次从God_Dog,Dog,God检索
def specialty(self):
print('my')
God.specialty(self)
super().specialty()#常用的方式,先导入先用
Dog.specialty(self)
a = God_Dog()
a.specialty()
print(God_Dog.mro()) #查看检索方法时的顺序
#相同的方法调用时按照先传入先调用
my
God
aaaaa
aaaaa
[<class '__main__.God_Dog'>, <class '__main__.Dog'>, <class '__main__.God'>, <class 'object'>]
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!