一.继承
#子类继承父类的属性和特征
#有两种技术:
1.调用未绑定的父类方法
例如:
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 Shark(Fish):
def __init__(self): #此处会覆盖父类的方法
Fish.__init__(self) #调用父类的方法,而此处的self是子类的实例对象,即未绑定的父类方法
self.hungry = True
def eat(self):
if self.hungry:
print("好吃!")
self.hungry = False
else:
print("吃饱了")
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 Shark(Fish):
def __init__(self): #此处会覆盖父类的方法
super().__init__() #()内不需要参数
self.hungry = True
def eat(self):
if self.hungry:
print("好吃!")
self.hungry = False
else:
print("吃饱了")
示例代码:
class DerivedclassName(BaseClassName): #DerivedclassName叫做子类,(BaseClassName)括号内为基类,父类或超类
#以下为子类,父类的例子
>>>class Parent: #定义一个类,作为父类
def hello(self):
print('正在调用父类...')
>>>class Child(Parent): #再定义一个类,Child作为子类,Child(Parent)叫做继承了Parent父类的子类
pass
>>>p = Parent() #类的实例化
>>>p.hello()
正在调用父类...
>>>c = Child()
>>>c.hello()
正在调用父类... #Child()继承了Parent父类的属性
二.多重继承
同时继承多个父类的属性和方法
示例:
class DerivedclassName(Base1, Base2, Base3): #()内写入多个父类的名字即可
.........
三.注意
如果子类中定义与父类同名的方法或属性,则会自动覆盖父类对应的方法或属性,父类不受影响
例如:
>>>class Parent:
def hello(self):
print('正在调用父类...')
>>>p = Parent()
>>>p.hello()
正在调用父类...
>>>class Child(Parent):
def hello(self): #定义一个和父类同样的变量名
print('正在调用子类...')
>>>c = Child()
c.hello()
正在调用子类... #父类的变量名被覆盖,但父类不受影响