Python面向对象
多态
1 、传入的参数不一定是父类型,只要传入的类里面有和基础类型有相同的方法就类似实现了多态的功能,案例如下:
Python面向对象
多态
1 、传入的参数不一定是父类型,只要传入的类里面有和基础类型有相同的方法就类似实现了多态的功能,案例如下:
class Animal(object):
def run(self):
print("animal is run")
def twice(self,animal):
animal.run()
class Dog(Animal):
def run(self):
print("dog is run")
class Cat(Animal):
def run(self):
print("cat is run")
class Tan(Animal):
def test(self):
print("ninhao")
# 这个方法没有继承Animal ,但是有一个run()方法,也实现了类似多态的功能!
class Timer():
def run(self):
print("Start")
#dog = Dog()
#dog.run()
#print(isinstance(dog, Dog))
#print(isinstance(dog, Animal))
animal = Animal()
animal.twice(Dog())
animal.twice(Tan())
animal.twice(Timer())