Python:随机选择执行列出的所有函数调用

xqkwcwgp  于 2023-01-04  发布在  Python
关注(0)|答案(2)|浏览(162)

我被一个简单的问题困住了在函数中使用choice时,似乎所有函数都被执行,而只有一个函数应该被执行。2例如:

from ordereddict import OrderedDict
from random import choice

def PrintStrings():
    Text = choice(["Gutentag!", "Ni hao!", "Hola!"])
    print "Chosen Text is:", Text
    return Text

class Greeting():
    fields = OrderedDict([
         ("Morning",     "Hi"),
         ("Afternoon",   "Good Afternoon!"),
         ("Evening",     "Good Evening!"),
    ])

    def change(self):
        self.fields["Morning"] = "Good morning!"

    def changerandom(self, n = 1): 
        function=[
                    {self.fields["Morning"]: PrintStrings()},
                    {self.fields["Afternoon"]: PrintStrings()},
                    {self.fields["Evening"]: PrintStrings()},
                 ]
        result = {}
        for i in range(n):
            result.update(choice(function))
            print "Updated string:",result
            return result

text = Greeting()
text.change()
text.changerandom()

运行此脚本时,我将获得所有3个

{self.fields["Morning"]: PrintStrings()},
                    {self.fields["Afternoon"]: PrintStrings()},
                    {self.fields["Evening"]: PrintStrings()},

执行,而不应该执行。此脚本返回:

Chosen Text is: Ni hao!
Chosen Text is: Gutentag!
Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}

预期结果为:

Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}
yrdbyhpb

yrdbyhpb1#

撇开一些奇怪的数据结构选择不谈,您正在function中调用一个函数。删除括号'以便将函数作为 object 传递。
PrintStrings() -〉PrintStrings
下面是获得所需输出的可能解决方案:

def changerandom(self, n = 1): 
    result = {}
    for i in range(n):
        key_choice = Greeting.fields[choice(Greeting.fields.keys())]
        result[key_choice] = PrintStrings()
        print "Updated string:", result
        return result

使用这种方法,我们获取随机密钥,并在同一次迭代中调用PrintStrings()

qojgxg4l

qojgxg4l2#

对象将为您提供一种仅在序列化而非示例化时运行代码的方法:

class PrintStrings(object):
    def __init__(self):
        self.text = None
    def __str__(self):
        if self.text is None:
            text = choice(["Gutentag!", "Ni hao!", "Hola!"])
            print "Chosen Text is:", text
        return text
    def __repr__(self):
        return str(self)

代码的其余部分可以按原样使用,用这个类替换PrintStrings函数。

相关问题