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 (???)
I'm new to Python and am making a game as part of the LPTHW. My shoot function is supposed to disable a limb by setting it to false, but it doesn't edit the boolean at all. This might seem a bit redundant considering that I can set the boolean directly, but the shoot function will calculate a lot more than just changing a boolean. Help would be greatly appreciated.
Python passes its object references by value, so by doing limb = False
you're assigning a new object reference with the value False
to the parameter limb
, not modifying the object originally held by the parameter. (Well, technically it's not a "new" reference, as I believe True
, False
, and None
are all singletons in Python.)
Here's something that would work, however.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With