类继承,多态
类继承,多态
重写父类
class Animal:
a_type="哺乳动物"
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
print('父类的构造方法')
def eating(self):
print("%s is eating..."%(self.name))
class Peason(Animal):
a_type = "高级哺乳动物"
def __init__(self,name,age,sex,hobbie):
super(Peason,self).__init__(name,age,sex) #先执行父类的方法
self.hobbie=hobbie
print('子类的构造方法')
def eating(self):
print('%s在优雅的吃。。。'%(self.name))
p1=Peason('刘一骏','24','M','游戏')
p1.eating()
结果
父类的构造方法
子类的构造方法
刘一骏在优雅的吃。。。
多继承
- 深度优先
- 广度优先
封装
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
self.__life_val=100 #私有变量 私有属性
def get_life_val(self):
print('生命值还有%s'%self.__life_val)
return self.__life_val
a=Person('刘一骏',22)
print(a.__life_val)
结果:AttributeError: 'Person' object has no attribute '__life_val'
a.get_life_val()
结果:生命值还有100
封装方法
def __breath(self):
print('%s is breathing...'%self.name)
def got_attack(self):
self.__life_val-=20
print('被攻击了,生命值减了20')
self.__breath()
return self.__life_val
a.got_attack()
a.get_life_val()
被攻击了,生命值减了20
刘一骏 is breathing...
生命值还有80
多态
class Dog:
def sound(self):
print('汪汪汪。。。。')
class Cat:
def sound(self):
print('喵喵喵。。。。')
def make_sound(obj):
'''统一调用接口'''
obj.sound()
d=Dog()
c=Cat()
make_sound(d)
make_sound(c)
汪汪汪。。。。
喵喵喵。。。。
- 抽象类实现多态
class Document:
def __init__(self,name):
self.name=name
def show(self):
raise NotImplementedError("Subclasss must implement abstract method")
#子类调用的时候直接报错,子类必须重新写
class Pdf(Document):
def show(self):
return "Show pdf contents!"
class Word(Document):
def show(self):
return "Show word contents!"
a=Pdf('联系方式.pdf')
print(a.show())
Show pdf contents!
class Pdf(Document):
pass
# def show(self):
# return "Show pdf contents!"
raise NotImplementedError("Subclasss must implement abstract method")
NotImplementedError: Subclasss must implement abstract method
a=Pdf('联系方式.pdf')
b=Word('护士.docx')
for o in [a,b]:
print(o.show())
Show pdf contents!
Show word contents!