这是我的代码:
from __future__ import print_function
import random
from random import shuffle
from random import randint
class ship:
def __init__(self):
self.database_scientific = 100
self.database_cultural = 100
def move_on(self):
def _do_damage(self):
self = self - randint(5,30)
print(module)
system_list = [
'scientific database',
'cultural database'
]
system_list_damaged = {
'scientific database': _do_damage(self.database_scientific),
'cultural database': _do_damage(self.database_cultural)
}
if randint(0,10) >= 1:
encounter_type = randint(1,4)
vulnerable_system = system_list[0]
vulnerable_system_number_two = system_list[1]
if encounter_type == 1:
print("\n[1] Allow it to hit %s. \n[2] Rotate so it hits another part of the ship." % vulnerable_system)
choice = raw_input("\n> ")
if choice == 1 and vulnerable_system == "surface probes":
print("\nThe asteroid crashes into the ship and knocks one of the surface probes loose.")
self.surface_probes = self.surface_probes - 1
elif choice == 1:
print("\nThe asteroid crashes into the %s causing irreparable damage." % vulnerable_system)
for vulnerable_system in system_list_damaged.keys():
system_list_damaged[vulnerable_system](self)
break
s = ship()
s.move_on()
当我初始化move_on()定义时没有明确告知它时正在执行_do_damage()。任何人都能解释为什么会这样吗?我找不到一个好的答案或解决方案。我最初在move_on()之外有_do_damage(),但这不允许我调用_do_damage()定义......
答案 0 :(得分:0)
您将函数调用存储为字典中的值。 存储函数调用的返回值,不是函数本身。要调用存储在字典中的函数,
system_list_damaged = {
'scientific database': _do_damage,
}
# call:
system_list_damaged['scientific database'](self.database_scientific)
从system_list
中选择一个随机列表元素(根据您的评论),
from random import choice
element = choice(system_list)
现在,为了简化这一切,你可以这样做:
from random import choice
system_list_damaged = {
'scientific database': [_do_damage, self.database_scientific]
'cultural database': [_do_damage, self.database_cultural]
}
# and to call a random one,
function_to_call = choice(system_list_damaged.keys())
system_list_damaged[function_to_call][0](function_to_call[1])