17. Class Methods¶
In addition to attributes, classes may have methods. A method is a function
that exists inside of a class. Expanding the earlier example of a
from the review problem 1 above, the code below adds a method for a dog barking.
1class Dog(): 2 def __init__(self): 3 self.age = 0 4 self.name = "" 5 self.weight = 0 6 7 def bark(self): 8 print("Woof")
The method definition is contained in lines 7-8 above. Method definitions in a
class look almost exactly like function definitions. The big difference is the
addition of a parameter
self on line 7. The first parameter of any method
in a class must be
self. This parameter is required even if the function
does not use it.
Here are the important items to keep in mind when creating methods for classes:
Attributes should be listed first, methods after.
The first parameter of any method must be self.
Method definitions are indented exactly one tab stop.
Methods may be called in a manner similar to referencing attributes from an object. See the example code below.
1my_dog = Dog() 2 3my_dog.name = "Spot" 4my_dog.weight = 20 5my_dog.age = 3 6 7my_dog.bark()
Line 1 creates the dog. Lines 3-5 set the attributes of the object. Line 7
bark function. Note that even through the
bark function has
self, the call does not pass in anything. This is because
the first parameter is assumed to be a reference to the dog object itself.
Behind the scenes, Python makes a call that looks like:
# Example, not actually legal Dog.bark(my_dog)
bark function needs to make reference to any of the attributes,
then it does so using the
self reference variable. For example, we can
Dog class so that when the dog barks, it also prints out the
dog’s name. In the code below, the name attribute is accessed using a dot
operator and the
def bark(self): print("Woof says", self.name)
Attributes are adjectives, and methods are verbs.
17.1. Example: Ball Class¶
This example code could be used as part of a program to draw and keep track of a ball. Having all the parameters contained in a class makes data management easier.
1class Ball(): 2 def __init__(self): 3 # --- Class Attributes --- 4 # Ball position 5 self.x = 0 6 self.y = 0 7 8 # Ball's vector 9 self.change_x = 0 10 self.change_y = 0 11 12 # Ball size 13 self.size = 10 14 15 # Ball color 16 self.color = [255, 255, 255] 17 18 # --- Class Methods --- 19 def move(self): 20 self.x += self.change_x 21 self.y += self.change_y 22 23 def draw(self): 24 arcade.draw_circle_filled(self.x, self.y, self.size, self.color )
Below is the code that would go ahead of the main program loop to create a ball and set its attributes:
1the_ball = Ball() 2the_ball.x = 100 3the_ball.y = 100 4the_ball.change_x = 2 5the_ball.change_y = 1 6the_ball.color = [255, 0, 0]
This code would go inside the main loop to move and draw the ball:
Here’s where we separate the true programmers from the want-to-be’s. Understanding class references. Take a look at the following code:
1class Person(): 2 def __init__(self): 3 self.name = "" 4 self.money = 0 5 6 7def main(): 8 bob = Person() 9 bob.name = "Bob" 10 bob.money = 100 11 12 nancy = Person() 13 nancy.name = "Nancy" 14 15 print(bob.name, "has", bob.money, "dollars.") 16 print(nancy.name, "has", nancy.money, "dollars.") 17 18 19main()
The code above has nothing new. But the code below does:
1class Person(): 2 def __init__(self): 3 self.name = "" 4 self.money = 0 5 6 7def main(): 8 bob = Person() 9 bob.name = "Bob" 10 bob.money = 100 11 12 nancy = bob 13 nancy.name = "Nancy" 14 15 print(bob.name, "has", bob.money, "dollars.") 16 print(nancy.name, "has", nancy.money, "dollars.") 17 18 19main()
See the difference on line 12?
A common misconception when working with objects is to assume that the
bob is the
Person object. This is not the case. The
bob is a reference to the
Person object. That is, it
stores the memory address of where the object is, and not the object itself.
bob actually was the object, then line 9 could create a copy of the
object and there would be two objects in existence. The output of the program
would show both Bob and Nancy having 100 dollars. But when run, the program
outputs the following instead:
Nancy has 100 dollars. Nancy has 100 dollars.
bob stores is a reference to the object. Besides reference, one may
call this address, pointer, or handle. A reference is an address in
computer memory for where the object is stored. This address is a hexadecimal
number which, if printed out, might look something like
0x1e504. When line 9
is run, the address is copied rather than the entire object the address points
to. See the figure below.
We can also run this in www.pythontutor.com to see how both of the variables are pointing to the same object.
17.2. Functions and References¶
Look at the code example below. Line 1 creates a function that takes in a
number as a parameter. The variable
money is a variable that contains a
copy of the data that was passed in. Adding 100 to that number does not change
the number that was stored in
bob.money on line 11. Thus, the print
statement on line 14 prints out 100, and not 200.
1def give_money1(money): 2 money += 100 3 4 5class Person(): 6 def __init__(self): 7 self.name = "" 8 self.money = 0 9 10 11def main(): 12 bob = Person() 13 bob.name = "Bob" 14 bob.money = 100 15 16 give_money1(bob.money) 17 print(bob.money) 18 19main()
Running on PythonTutor we see that there are two instances of the
money variable. One is a copy and local to the give_money1 function.
Look at the additional code below. This code does cause
bob.money to increase
1def give_money2(person): 2 person.money += 100 3 4give_money2(bob) 5print(bob.money)
Why is this? Because
person contains a copy of the memory address of the
object, not the actual object itself. One can think of it as a bank account
number. The function has a copy of the bank account number, not a copy of the
whole bank account. So using the copy of the bank account number to deposit
100 dollars causes Bob’s bank account balance to go up.
Arrays work the same way. A function that takes in an array (list) as a parameter and modifies values in that array will be modifying the same array that the calling code created. The address of the array is copied, not the entire array.
17.3. Review Questions¶
Create a class called
Cat. Give it attributes for name, color, and weight. Give it a method called
Create an instance of the cat class, set the attributes, and call the
Create a class called
Monster. Give it an attribute for name and an integer attribute for health. Create a method called
decrease_healththat 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.
17.4. Avoid This Mistake¶
Put everything for a method into just one definition. Don’t define it twice. For example:
1# Wrong: 2class Dog(): 3 def __init__(self): 4 self.age = 0 5 self.name = "" 6 self.weight = 0 7 8 def __init__(self): 9 print("New dog!")
The computer will just ignore the first
__init__ and go with the last
definition. Instead do this:
1# Correct: 2class Dog(): 3 def __init__(self): 4 self.age = 0 5 self.name = "" 6 self.weight = 0 7 print("New dog!")
A constructor can be used for initializing and setting data for the object. The example Dog class above still allows the name attribute to be left blank after the creation of the dog object. How do we keep this from happening? Many objects need to have values right when they are created. The constructor function can be used to make this happen. See the code below:
1class Dog(): 2 3 def __init__(self, new_name): 4 """ Constructor. """ 5 self.name = new_name 6 7 8def main(): 9 # This creates the dog 10 my_dog = Dog("Spot") 11 12 # Print the name to verify it was set 13 print(my_dog.name) 14 15 # This line will give an error because 16 # a name is not passed in. 17 her_dog = Dog() 18 19main()
On line 3 the constructor function now has an additional parameter named
new_name. The value of this parameter is used to set the name attribute
Dog class on line 8. It is no longer possible to create a
Dog class without a name. The code on line 15 tries this. It will cause a
Python error and it will not run. A common mistake is to name the parameter of
__init__ function the same as the attribute and assume that the values
will automatically synchronize. This does not happen.
17.5. Review Questions¶
Should class names begin with an upper or lower case letter?
Should method names begin with an upper or lower case letter?
Should attribute names begin with an upper or lower case letter?
Which should be listed first in a class, attributes or methods?
What are other names for a reference?
What is another name for instance variable?
What is the name for an instance of a class?
Create a class called Star that will print out “A star is born!” every time it is created.
Create a class called Monster with attributes for health and a name. Add a constructor to the class that sets the health and name of the object with data passed in as parameters.
Another powerful feature of using classes and objects is the ability to make use of inheritance. It is possible to create a class and inherit all of the attributes and methods of a parent class.
For example, a program may create a class called
Boat which has all the
attributes needed to represent a boat in a game:
1class Boat(): 2 def __init__(self): 3 self.tonnage = 0 4 self.name = "" 5 self.is_docked = True 6 7 def dock(self): 8 if self.is_docked: 9 print("You are already docked.") 10 else: 11 self.is_docked = True 12 print("Docking") 13 14 def undock(self): 15 if not self.is_docked: 16 print("You aren't docked.") 17 else: 18 self.is_docked = False 19 print("Undocking")
To test out our code:
1b = Boat() 2 3b.dock() 4b.undock() 5b.undock() 6b.dock() 7b.dock()
You are already docked. Undocking You aren't docked. Docking You are already docked.
(If you watch the video for this section of the class, you’ll note that the “Boat” class in the video doesn’t actually run. The code above has been corrected but I haven’t fixed the video. Use this as a reminder, no matter how simple the code and how experienced the developer, test your code before you deliver it!)
Our program also needs a submarine. Our submarine can do everything a boat can,
plus we need a command for
submerge. Without inheritance we have two options.
One, add the
submerge()command to our boat. This isn’t a great idea because we don’t want to give the impression that our boats normally submerge.
Two, we could create a copy of the
Boatclass and call it
Submarine. In this class we’d add the
submerge()command. This is easy at first, but things become harder if we change the
Boatclass. A programmer would need to remember that we’d need to change not only the
Boatclass, but also make the same changes to the
Submarineclass. Keeping this code synchronized is time consuming and error-prone.
Luckily, there is a better way. Our program can create child classes that will inherit all the attributes and methods of the parent class. The child classes may then add fields and methods that correspond to their needs. For example:
1class Submarine(Boat): 2 def submerge(self): 3 print("Submerge!")
Line 1 is the important part. Just by putting
Boat in between the
parentheses during the class declaration, we have automatically picked up
every attribute and method that is in the Boat class. If we update
then the child class
Submarine will automatically get these updates.
Inheritance is that easy!
The next code example is diagrammed out in the figure below.
1class Person(): 2 def __init__(self): 3 self.name = "" 4 5class Employee(Person): 6 def __init__(self): 7 # Call the parent/super class constructor first 8 super().__init__() 9 10 # Now set up our variables 11 self.job_title = "" 12 13class Customer(Person): 14 def __init__(self): 15 super().__init__() 16 self.email = "" 17 18def main(): 19 john_smith = Person() 20 john_smith.name = "John Smith" 21 22 jane_employee = Employee() 23 jane_employee.name = "Jane Employee" 24 jane_employee.job_title = "Web Developer" 25 26 bob_customer = Customer() 27 bob_customer.name = "Bob Customer" 28 bob_customer.email = "email@example.com" 29 30main()
Person between the parentheses on lines 5 and 13, the
programmer has told the computer that Person is a parent class to both
Customer. This allows the program to set the name
attribute on lines 19 and 22.
Methods are also inherited. Any method the parent has, the child class will have too. But what if we have a method in both the child and parent class?
We have two options. We can run them both with
super() keyword. Using
super() followed by a dot operator, and then finally a method name
allows you to call the parent’s version of the method.
The code above shows the first option using
super where we run not only the
child constructor but also the parent constructor.
If you are writing a method for a child and want to call a parent method, normally it will be the first statement in the child method. Notice how it is in the example above.
All constructors should call the parent constructor because then you’d have a child without a parent and that is just sad. In fact, some languages force this rule, but Python doesn’t.
The second option? Methods may be overridden by a child class to provide
different functionality. The example below shows both options. The
Employee.report overrides the
Person.report because it never calls
and runs the parent
report method. The
Customer report does call the
parent and the report method in
Customer adds to the
1class Person(): 2 def __init__(self): 3 self.name = "" 4 5 def report(self): 6 # Basic report 7 print("Report for", self.name) 8 9class Employee(Person): 10 def __init__(self): 11 # Call the parent/super class constructor first 12 super().__init__() 13 14 # Now set up our variables 15 self.job_title = "" 16 17 def report(self): 18 # Here we override report and just do this: 19 print("Employee report for", self.name) 20 21class Customer(Person): 22 def __init__(self): 23 super().__init__() 24 self.email = "" 25 26 def report(self): 27 # Run the parent report: 28 super().report() 29 # Now add our own stuff to the end so we do both 30 print("Customer e-mail:", self.email) 31 32def main(): 33 john_smith = Person() 34 john_smith.name = "John Smith" 35 36 jane_employee = Employee() 37 jane_employee.name = "Jane Employee" 38 jane_employee.job_title = "Web Developer" 39 40 bob_customer = Customer() 41 bob_customer.name = "Bob Customer" 42 bob_customer.email = "firstname.lastname@example.org" 43 44 john_smith.report() 45 jane_employee.report() 46 bob_customer.report() 47 48main()
17.6. Is-A and Has-A Relationships¶
Classes have two main types of relationships. They are “is a” and “has a” relationships.
A parent class should always be a more general, abstract version of the
child class. This type of child to parent relationship is called an
is a relationship. For example, a parent class
Animal could have a child
Dog. The dog is an animal.
Dog class could have a child class Poodle. The poodle is a dog, and
is an animal.
It does not work the other way! A dolphin is a mammal, but a
mammal is not always a dolphin. So the class
Dolphin should never
be a parent to a class
Unrelated items that do not pass the is a test should not form parent/child
relationships. For example, a class
Table should not be a
parent to a class
Chair because a chair is not a table.
The other type of relationship is the has a relationship. These relationships
are implemented in code by class attributes. A dog has a name, and so
Dog class has an attribute for name. Likewise a person could have
a dog, and that would be implemented by having the Person class have
an attribute for
Person class would not derive from
because that would be some kind of insult.
Looking at the prior code example we can see:
Employee is a person.
Customer is a person.
Person has a name.
Employee has a job title.
Customer has an e-mail.
17.6.1. Static Variables vs. Instance Variables¶
The difference between static and instance variables is confusing. Thankfully it isn’t necessary to completely understand the difference right now. But if you stick with programming, it will be. Therefore we will briefly introduce it here.
There are also some oddities with Python that kept me confused the first several years I’ve made this book available. So you might see older videos and examples where I get it wrong.
An instance variable is the type of class variable we’ve used so far. Each instance of the class gets its own value. For example, in a room full of people each person will have their own age. Some of the ages may be the same, but we still need to track each age individually.
With instance variables, we can’t just say “age” with a room full of people. We need to specify whose age we are talking about. Also, if there are no people in the room, then referring to an age when there are no people to have an age makes no sense.
With static variables the value is the same for every single instance of the
class. Even if there are no instances, there still is a value for a static
variable. For example, we might have a
count static variable for the number
Human classes in existence. No humans? The value is zero, but the
count variable still exists.
In the example below,
ClassA creates an instance variable.
creates a static variable.
1# Example of an instance variable 2class ClassA(): 3 def __init__(self): 4 self.y = 3 5 6# Example of a static variable 7class ClassB(): 8 x = 7 9 10def main(): 11 # Create class instances 12 a = ClassA() 13 b = ClassB() 14 15 # Two ways to print the static variable. 16 # The second way is the proper way to do it. 17 print(b.x) 18 print(ClassB.x) 19 20 # One way to print an instance variable. 21 # The second generates an error, because we don't know what instance 22 # to reference. 23 print(a.y) 24 print(ClassA.y) 25 26main()
In the example above, lines 16 and 17 print out the static variable. Line 17 is the “proper” way to do so. Unlike before, we can refer to the class name when using static variables, rather than a variable that points to a particular instance. Because we are working with the class name, by looking at line 17 we instantly can tell we are working with a static variable. Line 16 could be either an instance or static variable. That confusion makes line 17 the better choice.
Line 22 prints out the instance variable, just like we’ve done in prior
examples. Line 23 will generate an error because each instance of y is
different (it is an instance variable after all) and we aren’t telling the
computer what instance of
ClassA we are talking about.
17.7. Instance Variables Hiding Static Variables¶
This is one “feature” of Python I dislike. It is possible to have a static variable, and an instance variable with the same name. Look at the example below:
1# Class with a static variable 2class ClassB(): 3 x = 7 4 5def main(): 6 # Create a class instance 7 b = ClassB() 8 9 # This prints 7 10 print(b.x) 11 12 # This also prints 7 13 print(ClassB.x) 14 15 # Set x to a new value using the class name 16 ClassB.x = 8 17 18 # This also prints 8 19 print(b.x) 20 21 # This prints 8 22 print(ClassB.x) 23 24 # Set x to a new value using the instance. 25 # Wait! Actually, it doesn't set x to a new value! 26 # It creates a brand new variable, x. This x 27 # is an instance variable. The static variable is 28 # also called x. But they are two different 29 # variables. This is super-confusing and is bad 30 # practice. 31 b.x = 9 32 33 # This prints 9 34 print(b.x) 35 36 # This prints 8. NOT 9!!! 37 print(ClassB.x) 38 39main()
Allowing instance variables to hide static variable caused confusion for me for many years!