2010-10-12 59 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