Start learning free

LESSON 285 OF 673 · FUNCTIONS & CLASSES

Methods in Python

Lesson

TL ; DR:

  • A method is a function that lives inside a class. Its first parameter is always self, which refers to the object the method is called on.


  • Define methods inside the class with def:

    class Dog:
        def __init__(self, name):
            self.name = name
    
        def bark(self):
            print("Woof! I am " + self.name)
    

  • Call it on an object with the dot operator (no need to pass self — Python does it automatically):

    dog.bark()
    


Full lesson:

So far you've added data to a class with attributes set in __init__. The other half of OOP is behavior — actions an object can perform. That's what methods are for.


The self parameter

Every method's first parameter is self, which Python passes automatically. Inside the method, you read and write attributes via self.name.

def bark(self):
    print("Woof! I am " + self.name)

Your task

Add a bark method (taking self) that prints "Woof! I am " followed by self.name.

Woof! I am Rex
STEP 1 OF 2
    Ctrl + Enter to check