Reputation: 31
So when i change variable health im trying to inform user that their health has changed by printing "Your health is %s". Heres how it looks like...
health=5
def start():
global health
health+=2
So I'm wondering is there a way to inform the user with some kind of overarching function that is not within this function start()
but outside it so that every time variable health is changed it prints that and that? I'm learning python so dont judge!
Upvotes: 1
Views: 1413
Reputation: 1826
We can create a subtype of int
.
class Health(int):
def __new__(cls, value):
return int.__new__(cls, value)
def __iadd__(self, other):
print(f"+{other} health")
return self.__class__(self + other)
def __isub__(self, other):
print(f"-{other} health")
return self.__class__(self - other)
This is a bit complicated, but an interesting ability.
In [1]: h = Health(10)
In [2]: h += 2
+2 health
In [3]: h -= 3
-3 health
In [4]: h
Out[4]: 9
But i prefer the approach of @timgeb
Upvotes: 0
Reputation: 3515
I think the easiest way is to define a function somewhere in your code:
health = 5
def main():
global health
def change_health(amount):
health += amount
print('your health went {} by {}'
.format('up' if amount > 0 else 'down',
abs(amount)))
change_health(-2)
This function uses the global variable health and changes it. Then as described, it prints out that message. The line 'up' if amount > 0 else 'down'
I thought was quite nifty: it results in either up
or down
being formatted depending if the number is positive or not.
The format string means each {}
will be replaced with whatever value is put in the .format()
call in their respective positions.
Upvotes: 2
Reputation: 149
health=5
def start():
new_health= health +2
print new_health, health
I believe this is what you are looking for. Since the your variable is global it could be changed anywhere in the your programme.So by printing both you can see that your original health does not change.
Upvotes: 0
Reputation: 78680
We can do better than what you are trying to do by having a Player
class with a custom __setattr__
hook.
class Player:
def __init__(self):
vars(self)['health'] = 100 # suppress __setattr__
def __setattr__(self, attr, value):
if attr == 'health':
print('health changed to {}'.format(value))
super().__setattr__(attr, value)
Of course, you can expand this class according to your needs. For example, you could add a name
attribute and print '{}'s health changed to {}'.format(self.name, value)
.
Demo:
>>> p = Player()
>>> p.health
100
>>> p.health += 2
health changed to 102
As a bonus, you now can have multiple players with different health levels at the same time and don't have to manage global variables.
Upvotes: 3