2 Star 3 Fork 3

celaraze / learning-python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
21.继承和多态.py 769 Bytes
一键复制 编辑 原始数据 按行查看 历史
class Animal(object):
def run(self):
print('Animal is running')
class Dog(Animal):
def run(self):
print('dog is running')
pass
class Cat(Animal):
def run(self):
print('cat is running')
pass
dog = Dog()
dog.run()
cat = Cat()
cat.run()
# 判断是否是Dog类型
print(isinstance(dog, Dog))
# 判断是否是Animal类型
print(isinstance(dog, Animal))
def run_twice(animal):
animal.run()
animal.run()
run_twice(Animal())
run_twice(Dog())
run_twice(Cat())
# 动态语言只需要保证对象有一个run()函数,就能被执行
# 静态语言需要对象必须是某个父类的子类才行
# 动态语言的鸭子类型,"只要看起来像鸭子,走起路来像鸭子",那么它就可以被看做是鸭子
Python
1
https://gitee.com/celaraze/learning-python.git
git@gitee.com:celaraze/learning-python.git
celaraze
learning-python
learning-python
master

搜索帮助