Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean not changing value

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.

like image 245
user1580165 Avatar asked Feb 20 '23 14:02

user1580165


1 Answers

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')
like image 134
JAB Avatar answered Feb 22 '23 03:02

JAB