简单的mark一下最近学到的关于继承的知识点(我三分钟记忆,所以需要写笔记)。
一.单向继承的基本格式:class DerivedClassName(BaseClassName):
其中DerivedClassName是子类,BaseClassName是父类,也可以叫做基类。
子类可以继承父类中的任何属性和方法。
简单举个例子:
#父类
class Parent:
age = 50 #属性
def hi(self):
print("正在调用父类...“)
#子类
class Child(Parent):
pass
p = Parent()
print(p.age)
-->50
p.hi()
-->正在调用父类...
c = Child()
print(c.age)
-->50
c.hi()
-->正在调用父类...
二.多重继承的基本格式:class DerivedClassName(BaseClassName1,BaseClassName2,BaseClassName3...):
简单举个例子:
class Base1:
def foo1(self):
print("我是Base1的foo1")
class Base2:
def foo2(self):
print("我是Base2的foo2")
class Base3:
def foo3(self):
print("我是Base3的foo3")
class A(Base1,Base2,Base3):
pass
a = A()
a.foo1()
a.foo2()
a.foo3()
三.如果子类中定义了与父类中同名的方法或者属性,那么子类中的方法或属性会自动覆盖父类中对应同名的方法或属性。
举个例子:
class Parent:
# 属性
age = 50
# 方法
def hi(self):
print("正在调用父类")
# 子类
class Child(Parent):
age = 20
def hi(self):
print("正在调用子类")
p = Parent()
print(p.age)
p.hi()
c = Child()
print(c.age)
c.hi()
分类对应的结果:
50
正在调用父类
20
正在调用子类
四.补充继承中存在__init__(self)的情况
__init__(self) 一般都是指构造函数
1.如果在父类中使用构造函数声明了对象的属性,子类中没有重新定义构造函数,子类会自动继承父类的属性。
举个例子:
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
调用:
ff = Fish()
print(ff.x, ff.y)
ff.move()
gg = GoldFish()
print(gg.x, gg.y)
gg.move()
运行结果:
4 8
我的位置是: 3 8
7 0
我的位置是: 6 0
1.如果在父类中使用构造函数声明了对象的属性,子类中重新定义构造函数,子类会自动覆盖父类的属性。
举个例子:
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 Shark(Fish):
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print("肚子饿了,要吃东西...")
else:
print("不饿...")
ff = Fish()
ff.move()
ss = Shark()
ss.move()
注意:这里我在Shark()中重新定义了__init__(self)函数,运行看一下结果。
提示我Shark对象中没有x属性。因为我在Shark()中重新定义了__init__(self)函数,所以它覆盖了父类中的self.x self.y属性,运作时没有找到self.x self.y就报错了。
解决方法有2种:
第一种:调用未绑定的父类方法
class Shark(Fish):
def __init__(self):
Fish.__init__(self)
self.hungry = True
def eat(self):
if self.hungry:
print("肚子饿了,要吃东西...")
else:
print("不饿...")
ss = Shark() ss.move()
运行也是成功的。
第二种:使用super函数,super函数的超级之处在于你不用给定任何基类的名字,super函数相当于找出当前类的父类并调用点后面的方法,是调用父类的一个方法。
class Shark(Fish):
def __init__(self):
super().__init__()
self.hungry = True
def eat(self):
if self.hungry:
print("肚子饿了,要吃东西...")
else:
print("不饿...")
ss = Shark() ss.move()
运行也是成功的。