关于python字符串的问题

时间:2010-10-12 08:01:55

标签: python string

我被要求编写一个应该以这种方式调用的函数

foo("Hello")

此函数还必须以这种方式返回值:

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

该任务已明确要求返回字符串值。任何人都可以在Python的概念中理解这个任务的目的并帮助我吗? 你能给我一个代码样本吗?

2 个答案:

答案 0 :(得分:0)

Functions

Lists

Classes

创建一个具有所需属性的类,然后从函数中返回实例列表。

答案 1 :(得分: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