#面向对象的三大特征:继承、多态、封装。
#一、单继承:
# 1.
class Animal: #没有父类,默认继承了顶级父类object类。
def __init__(self,name,aggr,hp):
self.name = name
self.aggr = aggr
self.hp = hp
class Person(Animal): #子类继承父类的属性和方法。
pass
class Dog(Animal): #当Person和Dog具有相同的属性的时候,可以通过继承父类来简化代码。
pass
p = Person('alex',10,9)
print(p.name)
d = Dog('jin',8,7)
print(d.name)
#2.派生属性和派生方法:在继承父类的属性或方法的基础上,增加新功能:
class Animal:
def __init__(self,name,aggr,hp):
self.name = name
self.aggr = aggr
self.hp = hp
def attack(self):
print('调用攻击技能')
class Person(Animal):
def __init__(self,name,aggr,hp,money): #子类想派生属性,需要把初始化方法和参数重写一遍,并且添加新参数。
Animal.__init__(self,name,aggr,hp) #调用父类的属性。
self.money = money #派生属性
def attack(self,dog):
Animal.attack(self) #调用父类的方法。
print('%s掉血'%dog) #派生方法
alex = Person('alex',10,9,200)
print(alex.name)
print(alex.money)
alex.attack('jin')
#3.当子类和父类的方法名一样的情况下,执行子类的方法:
class Animal:
def __init__(self,name,aggr,hp):
self.name = name
self.aggr = aggr
self.hp = hp
def attack(self):
print('调用攻击技能')
class Person(Animal):
def attack(self): #子类和父类的方法名一样。
print('执行子类的方法')
alex = Person('alex',100,80)
alex.attack() #结果:执行子类的方法
#4. super:
class Animal:
def __init__(self,name,aggr,hp):
self.name = name
self.aggr = aggr
self.hp = hp
def attack(self):
print('调用父类的攻击技能')
class Person(Animal):
def __init__(self,name,aggr,hp,money):
super().__init__(name,aggr,hp) #父类也叫超类,super()调用父类,相当于super(Person,self),所以__init__后面不需要self。
self.money = money
def attack(self,a):
super().attack()
print('战斗力提高百分之{}'.format(a))
alex = Person('alex',100,80,800)
print(alex.name)
alex.attack(80)
super(Person,alex).attack() #结果:调用父类的攻击技能。在类的外面也可以使用super:类的实例化对象调用父类的方法。