【发布时间】:2018-10-05 03:51:26
【问题描述】:
我对编程很陌生,我正在尝试找到最有效的方法来迭代对象以在每次传递时更新它的状态。我以为我可以使用 Python 3.6 中的字典来运行对象中的代码。我希望看到这样的输出:
Tank A is clean
dirty
Tank B is dirty
clean
最终切换了坦克对象模式。为什么这不起作用,从实例化的坦克中选择正确的 def 以运行的最有效方法是什么?
class Tank:
def __init__(self, mode, name):
self.mode = mode
self.name = name
def dirty(self):
print("%s is dirty"%(self.name))
self.mode = 'clean'
return self
def clean(self):
print("%s is clean"%(self.name))
self.mode = 'dirty'
return self
i = 0
tankList = []
tankList.append(Tank('clean', "Tank A"))
tankList.append(Tank('dirty', "Tank B"))
while i < 2:
#create the mode lookup
dict = {'clean': tankList[i].clean(), 'dirty': tankList[i].dirty()}
#update the tank mode
tankList[i] = dict[tankList[i].mode]
#display the tank mode
print(tankList[i].mode)
i += 1
【问题讨论】:
-
您展示了您希望代码打印/执行的操作,而不是当前执行的操作。这可能会对回答者有所帮助。
标签: python dictionary switch-statement