Methods That Change the Object
A method can also change the object it was called on. A birthday makes a pet one year older:
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
def birthday(self):
self.age += 1
rex = Pet("Rex", "dog", 3)
rex.birthday()
rex.birthday()
print(rex.age)5Each call of rex.birthday() adds 1 to Rex's age, and only to his, because self is rex. The method changes the object and returns nothing, so you call it on a line of its own, as you call names.append("Tom"). print(rex.birthday()) would make Rex older and print None.
A method can have more parameters than self. They come after it, and the call passes only them. This method feeds a pet, and it makes sure that the hunger never drops below 0:
class Pet:
def __init__(self, name, species, age):
self.name = name
self.species = species
self.age = age
self.hunger = 5
def feed(self, amount):
self.hunger -= amount
if self.hunger < 0:
self.hunger = 0
rex = Pet("Rex", "dog", 3)
rex.feed(2)
print(rex.hunger)
rex.feed(10)
print(rex.hunger)3
0That's an advantage of methods: the rule “never below 0” is written once, in the class, and every pet that's fed with feed() follows it. With a dictionary, every place in the program that changes the hunger would have to remember the rule.
Don't forget self. in front of an attribute you change. Without it, hunger -= amount doesn't touch the pet: hunger is then a local variable of the method, which has no value yet, and the program ends with UnboundLocalError: cannot access local variable 'hunger' where it is not associated with a value.
Instructions
- 1
Add a method
play(self)that increases the pet's hunger by 3, since playing makes a pet hungry. At the end of the program, callrex.play()and print the hunger again in the same way. The output is thenHunger: 5andHunger: 8. - 2
A pet can't be hungrier than 10. Add a condition to
play(): when the hunger would go over 10, it becomes 10. Then callrex.play()once more at the end and print the hunger:Hunger: 10.