简单理解多态性中的'for'循环

时间:2012-04-03 02:18:59

标签: python

class Animal:
    def __init__(self, name):    
        self.name = name
    def talk(self):              
        raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
    def talk(self):
        return 'Meow!'

class Dog(Animal):
    def talk(self):
        return 'Woof! Woof!'

animals = [Cat('Missy'),
           Dog('Lassie')]

for animal in animals:
    print animal.name + ': ' + animal.talk()

我想知道为什么" 动物中的动物"动物被带走?什么是动物代表什么? 这里的班级名称是动物。

3 个答案:

答案 0 :(得分:1)

Python中的for循环实际上是一个for-each循环。我们遍历集合中的每个元素(我们称之为animal)(我们称之为animals)。

答案 1 :(得分:1)

你正在看的是python中的for循环。该语句遍历有序​​集合(列表,字符串或文件对象),在您的情况下,它是Animal的列表。选择单词(object中的objects)是python的传统。

看看这段代码,看看你是否更了解它:)

iceCreams = ['Vanilla', 'Chocolate'] # A list of ice cream flavors
toppings = ['Gummy Bear', 'Cookies', 'Nuts', 'Chips']  # A list of toppings

# Looping through the ice creams
# for each ice cream in the ice cream list
for iceCream in iceCreams:
    # Looping through the toppings
    # for each topping in the topping list
    for topping in toppings:
        print('I like', iceCream, 'ice cream with', topping)

输出:

I like Vanilla ice cream with Gummy Bear
I like Vanilla ice cream with Cookies
I like Vanilla ice cream with Nuts
I like Vanilla ice cream with Chips
I like Chocolate ice cream with Gummy Bear
I like Chocolate ice cream with Cookies
I like Chocolate ice cream with Nuts
I like Chocolate ice cream with Chips

希望这有助于您了解它是如何工作的,以及以嵌套形式使用它。

答案 2 :(得分:0)

animals是您使用

行定义的类的列表
animals = [Cat('Missy'), Dog('Lassie')]

for animal in animals:行被称为语法糖,只是一种更简单的传统for循环方式。在这种情况下,迭代器变量称为animal,它等于您使用上述命令创建的动物列表的每个元素。