3️⃣

12.3 Methods

Methods

In addition to attributes, classes can also have methods. Methods are functions within the class that allow it to have certain functionalities.

class Tesla:
    def __init__(self, maxSpeed=120, color="red"):
        self.maxSpeed = maxSpeed
        self.color = color

    # a method; acts just like a function, but needs self keyword
    def drive(self):
        print("The car is now driving")
p1 = Tesla(140, "blue")
p1.drive()  # will print "The car is now driving"

View code on GitHub.

Why do the methods have self as a parameter? We'll get to this next section. For now, just know that these methods are instance methods, meaning that you have to call it using an instance.

💡

If you really want to know, there are types of methods like static and class methods that can be called directly from the class, unlike instance methods, and don't always require the self keyword. They are beyond the scope of the class though. You don't have to worry about them for now.

In the example above, the method drive() is called from the instance p1 and p1.drive() will result in "The car is now driving" being printed to the console. We don't need to pass anything to p1.drive() because self is automatically passed when it the method is called from an instance.

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.