2010-10-12 63 views
-2

我被要求写一个应该以这种方式问题有关Python字符串

foo("Hello") 

这个功能也有以这种方式返回值调用的函数:

[Hello(user = 'me', answer = 'no', condition = 'good'), 
Hello(user = 'you', answer = 'yes', condition = 'bad'), 
] 

任务有明确要求返回字符串值。任何人都可以在Python的概念中理解这个任务的目的,并帮助我解决这个问题吗? 你能否给我一个代码示例?

+0

老实说,我不知道这个问题是要求。你能否提供你有任何额外的信息? – aaronasterling 2010-10-12 08:09:50

+0

这是功课吗? – 2010-10-12 09:14:27

+0

我认为,可能你需要创建一个名为'Hello'的类来覆盖它的__str__'方法,并创建另一个返回Object Hello的列表(数组)的方法以获得所需的属性..... – shahjapan 2010-10-12 09:31:34

回答

0

这可能是这样的:

class Hello: 
    def __init__(self, user, answer, condition): 
     self.user = user 
     self.answer = answer 
     self.condition = condition 

def foo(): 
    return [Hello(user = 'me', answer = 'no', condition = 'good'), 
    Hello(user = 'you', answer = 'yes', condition = 'bad'), 
    ] 

foo函数的输出:

[<__main__.Hello instance at 0x7f13abd761b8>, <__main__.Hello instance at 0x7f13abd76200>] 

这是类实例(对象)的列表。

你可以用它们这样:

for instance in foo(): 
    print instance.user 
    print instance.answer 
    print instance.condition 

其中给出:

me 
no 
good 
you 
yes 
bad