1.多继承:
1.一个子类可以继承多个父类
2.父类中方法名相同时,调用顺序按照括号顺序依次调用
#Child类
from Father import Father
from Mother import Mother
class Child(Father,Mother):
def __init__(self,money,faceValue):
Father.__init__(self,money)
Mother.__init__(self,faceValue)
#father类
class Father:
def __init__(self,money):
self.money=money
def play(self):
print("play")
def func(self):
print("fun1")
#mother类
class Mother:
def __init__(self,faceValue):
self.faceValue=faceValue
def work(self):
print("work")
def eat(self):
print("eat")
def func(self):
print("fun2")
#多继承:一个子类可以继承多个父类
from Child import Child
def main():
pass
c=Child(100,200)
print(c.money,c.faceValue)
c.play()
c.work()
#父类中方法名相同时,调用顺序按括号顺序依次调用
c.func()
if __name__ == '__main__':
main()
2.多态(投喂动物案例)
1.多态:一种事物的多种形态
2.python中多态的作用:
让具有不同功能的函数可以使用相同的函数名,这样就可以用一个函数名调用不同内容(功能)的函数。
3.多态的特点:
1.只关心对象的实例方法是否同名,不关心对象所属的类型;
2.对象所属的类之间,继承关系可有可无;
3.多态的好处可以增加代码的外部调用灵活度,让代码更加通用,兼容性比较强;
4.多态是调用方法的技巧,不会影响到类的内部设计。
#动物类
class Animal:
def __init__(self,name):
self.name=name
def eat(self):
print(self.name+"吃")
#cat类
from Animal import Animal
class Cat(Animal):
def __init__(self,name):
self.name=name
# def eat(self):
# print(self.name+"吃")
#mouse类
class Mouse:
def __init__(self,name):
self.name=name
def eat(self):
print(self.name+"吃")
#person类
class Person:
# def feedCat(self,cat):
# print("给你食物")
# cat.eat()
# def feedMouse(self,mouse):
# print("给你食物")
# mouse.eat()
def feedAnimal(self,ani):
print("给你食物")
ani.eat()
#多态:一种事物的多种形态
from Cat import Cat
from Mouse import Mouse
from Person import Person
tom=Cat("tom")
jerry=Mouse("jerry")
tom.eat()
jerry.eat()
#定义一个人类,可以喂猫和老鼠吃东西
per=Person()
# per.feedCat(tom)
# per.feedMouse(jerry)
per.feedAnimal(tom)
per.feedAnimal(jerry)
3.对象属性和类属性
1.对象属性的优先级高于类属性
2.动态的给对象添加属性,只针对当前对象生效,对于类创建的其他对象没有作用
3.对象属性与类属性不要重名。重名时,对象属性会屏蔽类属性;仅当删除对象属性时,才能正常使用类属性。
#对象属性和类属性
class Person:
#类名属性(用类名来调用)
name="Persondxn"
#对象属性
def __init__(self,name):
self.name=name;
print(Person.name)
#对象属性的优先级高于类属性
pr1=Person("tom")
print(pr1.name)
#动态的给对象添加属性
pr1.age=18#只针对当前对象生效,对于类创建的其他对象没有作用
print(pr1.age)
#删除对象中的name属性,在调用中会使用到同名的类属性
del pr1.name
print(pr1.name)
#对象属性与类属性不要重名,因为对象属性会屏蔽类属性,
#仅当删除对象属性时,才能正常使用类属性