7.2. Methods#

A method is a function that belongs to a class that performs actions for objects of the class. A method is declared within the class declaration.

class Class_name:
    def method_name(self):
        commands to be executed

Where self is a parameter that refers to the current instance of the class. Lets add a method to our Member class, inside the Method class declaration, enter the following code.

def print(self):
    print("\nUniversity Member Details\n-------------------------")
    print(f"Name     : {self.name}")
    print(f"ID       : {self.ID}")

Here we have declared a print() method that prints the details of the object. At the end of your program enter the following code.

# Methods
abby = Member("Abby Anderson", 24135791)

print()
abby.print()

Run your program and you should see the following added to the console.

University Member Details
-------------------------
Name     : Abby Anderson
ID       : 24135791

Note

If we try to call the print() method on the ellie, joel or tommy objects Python will return an error since when those objects were created our Member class did not have a print() method. To use this method on these objects we will need to re-create them using the updated class declaration


7.2.1. Exercises#

Exercise 7.3

Add an attribute called speed to your Vehicle class from Exercise 7.1 and set it equal to 0. Write a method called accelerate() that increases the speed attribute by a given amount ensuring that it doesn’t exceed the maximum speed.

Use your method to accelerate the two vehicles using the following and print their speed:

  1. accelerate the Delorean to 88 mph

  2. accelerate the Batmobile to 150 mph

Exercise 7.4

Add a method to your Shape class from Exercise 7.2 called print() that prints the name of the shape and the number of edges it has.