7.1.6 - Functions and References

Now let's use the reference with a function.

def give_money(person): person.money += 100 class Person(): def __init__(self): self.name = "" self.money = 0 bob = Person() bob.name = "Bob" bob.money = 100 give_money(bob) print(bob.money)


And review it in www.pythontutor.com

ref_functAs you can see in this example the function takes as an argument a person which is a memory address of the object. Think of it as a bank account number. The function uses this copy of the account number to deposit 100 euros. This causes Bob's bank account balance to go up.

Exercise 1

In Thonny's scripting area create a program as follows:

  • Create a class called Cat with attributes for name, color and weight.
  • Create a method inside the class called meow.
  • Create an instance of the cat class, set the attributes, and call the meow method.

Exercise 1 answer

Exercise 2

In Thonny's scripting area create a program as follows:

  • Create a class called Monster with attributes name and an integer attribute for health.
  • Create a method called decrease_health that takes in a parameter amount and decreases the health by that much.
  • Inside that method, print that the animal died if health goes below zero.

Exercise 2 answer