Module 7 - Section 1 - Classes
Module 7 - Section 1 - Classes
- identify a class inside Python code
- present the necessary parts for constructing a class
- create code to construct a simple class
- create and use methods in a class
- distinguish the references from the objects of a class
- rewrite the classes code to implement constructors
7.1.3 - Class methods
In addition to attributes, classes may have methods. A method is a function that exists inside of a class. Changing the earlier example we create a class of a Dog and add a method for a dog bark. Copy the code below to the script area of Thonny, save it as dogClass and run it.
class Dog():
def __init__(self):
self.age = 0
self.name = ""
self.weight = 0
def bark(self):
print("Woof")
In the above code the method definition is a function inside the class. The big difference is the addition of the parameter self inside the definition parenthesis. 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. Write the following commands in CLI area of Thonny.
>>> my_dog = Dog()
>>> my_dog.name = "Jack"
>>> my_dog.weight = 14
>>> my_dog.age = 5
>>> my_dog.bark()
Now change the function inside the script to:
def bark(self):
print("Woof says", self.name)
save it, run it and write the following commands to CLI area.
>>> my_dog = Dog()
>>> my_dog.name = "Jack"
>>> my_dog.bark()