我卡上可能簡單的問題: 使用與選擇函數時,好像所有的人都被執行,而只有一個應該。 例子:的Python:執行列出的所有函數調用隨機選擇
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!'}
當你寫'{self.fields [ 「晨報」]:PrintStrings()}',它會調用'PrintStrings()'。創建'function'列表的整體執行 – njzk2
順便說一句 - 目前被稱爲'Text'變量應改爲被命名爲'text';請參閱[PEP-8,Python風格指南](https://www.python.org/dev/peps/pep-0008/)。 –