def shoot(self, limb):
if not limb:
pass
else:
limb = False
print Joe.body.head #prints out true
Bob.gun.shoot(Joe.body.head) # should print out false
print Joe.body.head #prints out true (???)
Run Code Online (Sandbox Code Playgroud)
我是Python新手,正在制作一款游戏作为LPTHW的一部分.我的拍摄功能应该通过将其设置为false来禁用肢体,但它根本不会编辑布尔值.考虑到我可以直接设置布尔值,这似乎有点多余,但是射击函数将计算的不仅仅是更改布尔值.非常感谢帮助.
Python通过值传递其对象引用,因此通过为参数limb = False分配带有值的新对象引用,而不是修改False参数limb最初保存的对象.(当然,从技术上这不是一个"新"的提法,因为我相信True,False和None在Python中的所有单身.)
然而,这是可行的.
def shoot(self, other, limbstr):
try:
if getattr(other, limbstr): # Levon's suggestion was a good one
setattr(other, limbstr, False)
except AttributeError:
pass # If the other doesn't have the specified attribute for whatever reason, then no need to do anything as the bullet will just pass by
Bob.gun.shoot(Joe.body, 'head')
Run Code Online (Sandbox Code Playgroud)