在子类中重用父类的方法或属性


# 在子类派生出的新的方法中重用父类的方法,有两种实现方式
# 方式一:指名道姓(不依赖继承)
# 方式二: super()(依赖继承)并且super 是按照mro顺序找的

# 方式一:
class Hoer:
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 Garen(Hoer):
camp = 'Demacia'
def __init__(self,nickname,life_value,aggresivity,weapon):
Hoer.__init__(self,nickname,life_value,aggresivity) # 指名道姓
self.weapon = weapon

def attack(self, enemy):
Hoer.attack(self, enemy) # 指名道姓
print('from Garen Class')

class Riven(Hoer):
camp = 'Noxus'

g1 = Garen('草丛伦',100,30,'金箍棒')
r1 = Riven('可爱的锐雯',80,50)

print(r1.life_value)
g1.attack(r1)
print(r1.life_value)

# 方式二:

class Hoer:
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 Garen(Hoer):
camp = 'Demacia'
def __init__(self,nickname,life_value,aggresivity,weapon):
super().__init__(nickname,life_value,aggresivity)
self.weapon = weapon

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

class Riven(Hoer):
camp = 'Noxus'


g1 = Garen('草丛伦',100,30,'金箍棒')
r1 = Riven('可爱的锐雯',80,50)

print(r1.life_value)
g1.attack(r1)
print(r1.life_value)


# -----------------------
class A:
def f1(self):
print('form class a')
super().f1()


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

class C(A,B):
pass

print(C.mro())
'''
<class '__main__.C'>
<class '__main__.A'>
<class '__main__.B'>
<class 'object'>
'''
c = C()
c.f1()
# super 继承是按照mro 顺序找的

posted on 2019-08-11 18:42  kingforn  阅读(840)  评论(0编辑  收藏  举报