Single inheritance
#所有类默认继承object
class Gun(object):
def __init__(self,width):
self.length = 100
self.width = width
def shoot(self):
print('bang')
class Wuzi(Gun):
pass
wuzi = Wuzi(3)
wuzi.shoot()
As shown in the above example, Gun is called the parent class, Wuzi is the subclass, Wuzi inherits Gun, and automatically inherits the properties and methods of the parent class. At this time, only one parent class is written in the brackets after Wuzi, which is called single inheritance.
Multiple inheritance
class Gun1(object):
def __init__(self):
self.length = 100
def shoot(self):
print('bang1')
class Gun2(object):
def __init__(self):
self.length = 200
def shoot(self):
print('bang2')
class Wuzi(Gun1,Gun2):
pass
wuzi = Wuzi()
wuzi.shoot()
At this time, the output is bang1, that is:
when a class inherits multiple parent classes, the same-named methods and properties of the first parent class are used by default
Subclass overrides the properties and methods of the parent class with the same name
class Gun1(object):
def __init__(self):
self.length = 100
def shoot(self):
print('bang1')
class Gun2(object):
def __init__(self):
self.length = 200
def shoot(self):
print('bang2')
class Wuzi(Gun1,Gun2):
def shoot(self):
print('bang3')
wuzi = Wuzi()
wuzi.shoot()
The output at this time is bang3