Py003-01-03子类使用父类属性和方法

子类使用父类属性和方法

指名道姓方式(不依赖继承)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

class Hero:
def __init__(self, nickname, life_value, aggresivity):
self.nickname = nickname
self.life_value = life_value
self.aggresivity = aggresivity

def attack(self, enemy):
enemy.life_value = self.aggresivity


class AX(Hero):
camp = '斧王'

def attack(self, enemy):
Hero.attack(self,enemy)
print('from Garen Class')

ax = AX('axe',100,50)
enemy = Hero('xxx',100,40)
ax.attack(enemy) # 50

子类想要个武器

很重复的写法

1
2
3
4
5
6
7
8
9
10
11
12
class AX(Hero):
camp = '斧王'
def __init__(self, nickname, life_value, aggresivity,weapon):
self.nickname = nickname
self.life_value = life_value
self.aggresivity = aggresivity
self.weapon = weapon
def attack(self, enemy):
Hero.attack(self,enemy)
print('from Garen Class')

ax = AX('axe',100,50,'金箍棒')

继续指名道姓

1
2
3
4
5
6
7
8
9
10
11
12
# 子类有武器 指名道姓
class AX(Hero):
camp = '斧王'
def __init__(self, nickname, life_value, aggresivity,weapon):
Hero.__init__(self, nickname, life_value, aggresivity)
self.weapon = weapon
def attack(self, enemy):
Hero.attack(self,enemy)
print('from Garen Class')

ax = AX('axe',100,50,'金箍棒')
print(ax.__dict__)

在子类派生出的新的方法中重用父类的方法,有两种方式

  • 指名道姓(不依赖继承)
  • super() (依赖继承)

调用方法

1
2
3
4
5
6
class AX(Hero):
camp = '斧王'
def attack(self, enemy):
# Hero.attack(self,enemy)
super(AX,self).attack(enemy)
print('from Garen Class')

使用父类的初始化方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# super
class AX(Hero):
camp = '斧王'
def __init__(self, nickname, life_value, aggresivity,weapon):
# 指名道姓
# Hero.__init__(self, nickname, life_value, aggresivity)
# python2中
super(AX,self).__init__(nickname, life_value, aggresivity)
# python3
super().__init__(nickname, life_value, aggresivity)
self.weapon = weapon
def attack(self, enemy):
Hero.attack(self,enemy)
print('from Garen Class')

ax = AX('axe',100,50,'金箍棒')
# print(ax.__dict__)

依赖继承的一道恶心的题

1
2
3
4
5
6
7
8
9
10
11
12
class A:
def f1(self):
print('from a')

class B:
def f1(self):
print('from b')

class C(A,B):
pass

print(C.mro()) # C A B Object

再看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class A:
def f1(self):
print('from a')
super().f1()

class B:
def f1(self):
print('from b')

class C(A,B):
pass

c = C()
c.f1()

结果:
from a
from b

C是依赖于继承的 所以会参照 C的mro列表查找 属性和方法