Python 列表理解与 for 循环

swa*_*wam 1 python for-loop list-comprehension

我有一堆类对象,“玩家”。当我使用 for 循环与 LC 时,我得到两种不同的行为......

Python 2.7

foo = something.blahObject
for i in foo:
    print i
Run Code Online (Sandbox Code Playgroud)

给我我想要的..

Object1
Object2
...
Run Code Online (Sandbox Code Playgroud)

如果我做

print [i for i in foo]
Run Code Online (Sandbox Code Playgroud)

给我...

[<something.blahObject at 0x10af....>, <something.blahObject at 0x10f....>]
Run Code Online (Sandbox Code Playgroud)

如果 for 循环和列表理解的行为相似,为什么我会得到不同的结果?我缺少什么?谢谢!

Kar*_*rin 5

列表中的对象将使用其__repr__方法,而自身打印的对象将使用__str__. 这就是为什么当您使用for循环(将使用__str__)和使用列表理解(将使用__repr__)时会得到不同的打印输出。

class ExampleObject(object):
    def __repr__(self):
        return 'ExampleRepresentation'

    def __str__(self):
        return 'ExampleString'

e = ExampleObject()
print e  # ExampleString
print [e]  # [ExampleRepresentation]
Run Code Online (Sandbox Code Playgroud)