一、子类和父类
1.子类可以继承所有父类的属性和方法
>>> class Parent:
def hello(self):
print('正在调用父类的方法')
>>> class Child(Parent):
pass
>>> p = Parent()
>>> p.hello()
正在调用父类的方法
>>> c = Child()
>>> c.hello()
正在调用父类的方法
2.子类中的属性和方法会自动覆盖父类中相应的属性和方法,即子类中无调用的方法,再到父类中寻找
>>> class Child(Parent):
def hello(self):
print('正在调用子类的方法')
>>> c = Child()
>>> c.hello()
正在调用子类的方法
>>>
3.super()函数:在子类中某个方法与父类方法重名,但仍想调用父类的方法,则使用super()函数
使用方法: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 Shark(Fish):
def __init__(self):
super().__init__()
self.hungry = True
def eat(self):
if self.hungry:
print('吃')
self.hungry = False
else:
print('吃完')
二、多重继承
class 子类(父类1, 父类2, 父类3):
尽量避免使用多从继承