Lesson 3 of 11
An instance method is a function defined inside a class. It's the behaviour half of object-oriented programming — what an object can do, alongside what it knows.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof!"
rex = Dog("Rex")
print(rex.speak())
Methods are defined with def and indented inside the class body. Like __init__, every one
takes self as its first parameter.
Methods use self to reach attributes
This is the whole point. A plain function would need the dog passed in; a method already has it.
def describe(dog_name, dog_age):
return f"{dog_name} is {dog_age}"
print(describe("Rex", 3))
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def describe(self):
return f"{self.name} is {self.age}"
print(Dog("Rex", 3).describe())
The method never needs the data handed to it — self gives it access to everything the object
holds.
Methods with extra parameters
self comes first, then whatever else you need:
class Dog:
def __init__(self, name):
self.name = name
def greet(self, other_name):
return f"{self.name} greets {other_name}!"
print(Dog("Rex").greet("Fido"))
You call it as rex.greet("Fido") — one argument, because Python supplies self from the object
on the left of the dot.
Methods that change the object
Methods can modify attributes, not just read them. This is how an object's state evolves over time.
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def reset(self):
self.count = 0
c = Counter()
c.increment()
c.increment()
print(c.count)
c.reset()
print(c.count)
Compare this with the global counter from lesson 4.5. That version needed a module-level
variable and the global keyword; this one keeps its state neatly inside the object, and you can
have as many independent counters as you want.
Methods calling other methods
Use self. to call one method from another:
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof!"
def speak_twice(self):
return f"{self.speak()} {self.speak()}"
print(Dog("Rex").speak_twice())
Forgetting self. gives NameError — inside a class, speak() on its own isn't in scope.
Try it yourself
Build a BankAccount with deposit and withdraw methods.
Checkpoint
- Instance methods are functions defined inside a class, with
selffirst. selfgives a method access to the object's attributes.- Calling
obj.method(x)passesobjasselfautomatically. - Methods can read and modify the object's state.
- Call one method from another with
self.other_method().
Questions about this lesson
Log in to ask a question.