赵娜0418

2020-08-03   阅读量: 801

Python编程

python类方法的多态性怎么理解

扫码加入数据分析学习群

我们创建一个for循环,遍历一个对象元组。然后调用函数而不关心每个对象是哪个类类型。我们假设这些方法实际上存在于每个类中。

class India():
def capital(self):
print("New Delhi is the capital of India.")

def language(self):
print("Hindi the primary language of India.")

def type(self):
print("India is a developing country.")

class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):
print("English is the primary language of USA.")

def type(self):
print("USA is a developed country.")

obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()

输出:
New Delhi is the capital of India.
Hindi the primary language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

1.1421 4 1 关注作者 收藏

评论(0)


暂无数据

推荐课程

推荐帖子