我正在尝试从列表的另一部分中调用对象,这显然不起作用。 有人可以解释我如何正确地做到这一点?先谢谢。
def doSLM(btn, *args):
if btn == 'btnBuild':
allObj = buildSnowLayers()
# Let's say that:
# allObj = [ground1, snow1, ground2, snow2, ground3, snow3]
allGrounds = allObj[::2]
# So we have:
# allGrounds = [ground1, ground2, ground3]
allSnowLayers = allObj[1::2]
# And:
# allSnowLayers = [snow1, snow2, snow3]
elif btn == 'btnClearScene':
# I need to pass 'allSnowLayers' in this part of
# the condition, but how?
for obj in allSnowLayers:
clearLayer(obj) # This function simply delete the object
修改:添加一些细节。对不起,如果不清楚,我还在学习......
答案 0 :(得分:0)
究竟是什么阻止您在条件之外创建列表?如果您需要访问它,无论条件如何解决,您也可以在正确的范围内定义它。
def doSLM(btn, *args): allObj = buildSnowLayers() allGrounds = allObj[::2] allSnowLayers = allObj[1::2] if btn == 'btnClearScene': # I need to pass 'allSnowLayers' in this part of # the condition, but how? for obj in allSnowLayers: clearLayer(obj) # This function simply delete the object
如果需要,可以在完成后清空中间列表,为其分配[]或“无”。如果您确实只需要在某些情况下填充列表,则可以将其定义为条件之外的空列表,然后将其填充到内部。
def doSLM(btn, *args): allSnowLayers = [] if btn == 'btnBuild': allObj = buildSnowLayers() # Let's say that: # allObj = [ground1, snow1, ground2, snow2, ground3, snow3] allGrounds = allObj[::2] # So we have: # allGrounds = [ground1, ground2, ground3] allSnowLayers = allObj[1::2] # And: # allSnowLayers = [snow1, snow2, snow3] elif btn == 'btnClearScene': # I need to pass 'allSnowLayers' in this part of # the condition, but how? for obj in allSnowLayers: clearLayer(obj) # This function simply delete the object
答案 1 :(得分:0)
我猜测您第一次了解scope。一般来说,描述变量范围超出了简单的StackOverflow问题范围,但是您需要确定从此函数范围之外访问allSnowLayers对象的方法。例如,考虑使用类和类属性。然后,每个按钮的行为可以通过单独的方法处理,而不是大的if / else开关。
例如:
class SLM:
def __init__(self):
layers = buildSnowLayers()
self.layers = layers
self.grounds = layers[::2]
self.snow_layers = layers[1::2]
def clearScene(self):
for obj in self.snow_layers:
clearLayer(obj)
在上面的示例中,实例化SLM类会创建一个SLM对象,该对象始终了解其"层","地面"的状态。和#34; snow_layers"属性,直到它被摧毁。如果你像
那样调用clearScene
slm = SLM()
slm.clearScene()
然后slm
会对clearLayer
属性的每个成员应用snow_layers
。它仍然知道该属性,因为它是对象的成员,而不仅仅是函数变量。