Python Methods: Functions Inside a Class
What Is a Method in Python?
A method is a function that lives inside a class. It describes something the object can do. You call it on an object with a dot: rocky.bark().
Think of it like the buttons on a TV remote. Every remote of the same model has the same buttons. But when you press "volume up" on yours, only your TV gets louder, not your neighbour's.
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name, "says Woof!")
rocky = Dog("Rocky")
lucky = Dog("Lucky")
rocky.bark()
lucky.bark()Rocky says Woof! Lucky says Woof!
The rules
- Define a method with
definside the class, indented under it. - Its first parameter is always
self, just like__init__. - Call it with
object.method(). Python passes the object in asself, sorocky.bark()runsbarkwithselfas Rocky. - Inside the method,
self.namereaches the object's own attributes. - Leave one blank line between the methods of a class (PEP 8, chapter 16).
You've called methods before
"sunny".upper(), pets.append("Rocky") and line.split() are all methods of built-in classes. Now you can write your own.
| Function | Method |
|---|---|
| defined on its own, with no indent | defined inside a class |
called by its name: greet() | called on an object: rocky.bark() |
| gets values only from its arguments | also gets the object, as self |
Avoid: forgetting self
class Dog:
def bark():
print("Woof!")
rocky = Dog()
rocky.bark()TypeError: Dog.bark() takes 0 positional arguments but 1 was given
"1 was given", even though the brackets are empty? That one is the object, passed in as self. Add self to the def line.
A method is a function inside a class. Call it on an object, and it gets that object as
self.