Skip to content
PythonObject-Oriented Programmingbeginner30 min read

Instance Methods and self

Learn how instance methods work, how self accesses the current object, and how methods read, modify, and return instance data.

In this lesson, you will learn

  • ✓Define an instance method inside a Python class.
  • ✓Explain what self refers to and how Python supplies it during a method call.
  • ✓Read and modify instance attributes through methods.
  • ✓Pass additional arguments to instance methods.
  • ✓Distinguish between printing a value and returning a value.
  • ✓Trace how multiple method calls change an object's state.
  • ✓Recognize common method-call errors and apply instance methods to small problems.

1. What is an instance method?

A method is a function defined inside a class. An instance method is a method designed to operate on a particular instance of that class.

For example, a Dog class might have a bark() method, while a Counter class might have an increment() method. These methods describe actions that their instances can perform.

An instance method is defined using def inside the class body. Its first parameter is conventionally named self. When you call the method through an instance, Python supplies that instance as the first argument automatically.

Defining a method does not mean that it runs immediately. The method executes when it is called.

Define and call an instance method

Define and call an instance method
python
class Greeter:
def greet(self):
print("Hi!")
 
greeter = Greeter()
greeter.greet()
Output
Hi!

class Greeter: defines the class. def greet(self): defines an instance method. Greeter() creates an instance and stores its reference in greeter. greeter.greet() calls the method on that instance. Python supplies greeter as the self argument automatically. The method prints Hi!.

Note

An instance method combines behavior with an object's state. The same method can operate on different objects because self identifies the current instance.

2. Understanding self

self is the conventional name for the first parameter of an instance method. It refers to the particular object on which the method is being called.

Python supplies the instance automatically when you use object.method(). This is why you normally write counter.increment(), not counter.increment(counter).

The name self is a convention, not a reserved Python keyword. Although another parameter name is technically possible, using self is the standard and strongly recommended practice.

Inside a method, self.name accesses the name attribute of the current instance. Similarly, self.balance accesses that instance's balance attribute.

If two objects call the same method, self refers to a different instance for each call. This allows a single method definition to work with many objects.

self identifies the calling object

self identifies the calling object
python
class Student:
def __init__(self, name):
self.name = name
 
def introduce(self):
print("My name is", self.name)
 
student_a = Student("Asha")
student_b = Student("Ravi")
 
student_a.introduce()
student_b.introduce()
Output
My name is Asha My name is Ravi

student_a and student_b are separate instances. During student_a.introduce(), self refers to student_a. During student_b.introduce(), self refers to student_b. The same method reads a different name depending on the calling instance.

Caution

When calling an instance method through an object, do not pass self yourself. Python supplies it automatically. Passing the object again can cause a TypeError because too many arguments are provided.

3. Reading instance attributes inside methods

An instance method can read an object's attributes through self. This lets the method use information stored when the object was initialized.

For example, a Rectangle object can store width and height. An area() method can read self.width and self.height to calculate the area.

Using instance attributes makes methods reusable. Instead of passing the same width and height every time, the method can use the values already stored on the object.

A method can read several attributes, calculate a result, and either print or return that result. Choosing between printing and returning is important and will be covered later in this lesson.

Calculate a rectangle's area

Calculate a rectangle's area
python
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
 
def area(self):
return self.width * self.height
 
rectangle = Rectangle(5, 3)
print(rectangle.area())
Output
15

The initializer stores width as 5 and height as 3. area() reads both values from the current instance. The expression self.width * self.height evaluates to 5 * 3, which is 15. return sends 15 back to the caller. The outer print displays the returned value.

Note

Use self.attribute to access state belonging to the current object. A method does not need to receive that same stored value as an argument again.

4. Modifying instance state through methods

Instance methods can do more than read attributes. They can update them, allowing an object to change its state in a controlled way.

For example, a Counter can store a value and provide an increment() method that adds one. A Lamp can store whether it is on and provide switch_on() and switch_off() methods.

When a method assigns to self.attribute, it changes the attribute on the current instance. The change remains after the method finishes because the instance continues to exist.

If another instance has its own attribute with the same name, changing the first instance normally does not change the second instance.

Build a Counter

Build a Counter
python
class Counter:
def __init__(self):
self.value = 0
 
def increment(self):
self.value += 1
 
counter = Counter()
print(counter.value)
counter.increment()
print(counter.value)
counter.increment()
print(counter.value)
Output
0 1 2

Creating the Counter initializes value to 0. The first print displays 0. increment() executes self.value += 1, changing the value to 1. The next call changes the value from 1 to 2. Each method call updates the same instance rather than creating a new Counter.

Note

An instance method can preserve state across multiple calls because its changes are made to the object, not just to a temporary local variable.

5. Passing arguments to instance methods

Instance methods can accept additional parameters after self. These parameters allow callers to supply information needed for an operation.

For example, deposit(amount) can accept the amount to add to a balance, and add_points(points) can accept how many points to add to a score.

When calling account.deposit(100), Python supplies account as self and 100 as amount. Inside the method, self identifies the account and amount contains the supplied number.

Method parameters behave like other function parameters. They can be positional or keyword arguments, and you can give them default values when that is appropriate.

When an argument must satisfy a rule, the method can validate it before changing the object's state.

Pass an amount to a method

Pass an amount to a method
python
class Wallet:
def __init__(self):
self.balance = 0
 
def add_money(self, amount):
self.balance += amount
 
wallet = Wallet()
wallet.add_money(50)
wallet.add_money(25)
print(wallet.balance)
Output
75

The wallet begins with a balance of 0. The first method call adds 50. The second method call adds 25 to the updated balance. The final balance is 0 + 50 + 25 = 75.

Caution

Method parameters do not automatically become instance attributes. Assign to self.attribute when a value must be stored on the object; otherwise, a parameter is simply a local name within the method.

6. print() versus return

One of the most important distinctions in Python is the difference between displaying a value and returning a value.

print() sends a human-readable representation to the output stream. It does not make the displayed value available as the function's result.

return sends a result back to the code that called the method. The caller can store it in a variable, print it, compare it, or use it in another calculation.

A method that reaches the end without a return statement returns None. A method that only prints a value also returns None unless it explicitly returns something else.

For calculations and reusable operations, returning a result is often more flexible than printing it directly. For methods whose purpose is to display a message, printing may be appropriate.

A method that prints

A method that prints
python
class Calculator:
def add(self, a, b):
print(a + b)
 
calculator = Calculator()
result = calculator.add(2, 3)
print(result)
Output
5 None

add() calculates 2 + 3 and prints 5. There is no return statement, so the method returns None. The variable result receives None. The final print displays None, even though the method already printed 5.

Note

Remember: print displays a value; return provides a value to the caller. A method can do both, but they serve different purposes.

7. Calling methods in sequence

A method can change an object's state, and a later method call can use that updated state. The order of calls therefore matters.

For example, a bank account might begin with a balance of 100. A deposit increases the balance, and a withdrawal decreases it. Each operation works with the balance left by the previous operation.

When tracing code, record the relevant attributes after every state-changing method call. Do not assume that a later call uses the original values.

A method can also call another instance method using self.other_method(). In that case, the nested call operates on the same current instance unless a different object is explicitly used.

Trace a sequence of state changes

Trace a sequence of state changes
python
class Counter:
def __init__(self):
self.value = 0
 
def increment(self):
self.value += 1
 
def add(self, amount):
self.value += amount
 
counter = Counter()
counter.increment()
counter.add(4)
counter.increment()
print(counter.value)
Output
6

Initial state: value = 0. After increment(): value = 1. After add(4): value = 5. After the next increment(): value = 6. The final print displays the current state, 6.

Note

When tracing methods, track the object and its state after every call. A method that changes an attribute affects what subsequent calls will observe.

8. Common mistakes and edge cases

Instance-method mistakes often involve missing self, incorrect arguments, confusing local variables with attributes, or assuming that a method returns a value when it only prints one.

Python reports many of these problems as TypeError or AttributeError. Understanding the method definition and the way it is called usually helps identify the issue.

A method can also receive an unexpected value. When that value could make the object's state invalid, validate it before performing the update.

A method that forgets self

A method that forgets self
python
class Greeter:
def greet():
print("Hello")
 
greeter = Greeter()
# greeter.greet() # Uncommenting this raises TypeError.
Output
No output

The method definition does not declare a parameter for the instance. Calling greeter.greet() automatically supplies greeter as the first argument. Because greet() declares no parameters, the call raises TypeError. The invalid call is commented out so the example itself runs without displaying output. The correct instance-method definition is def greet(self):.

Caution

A method can execute without an error and still fail to achieve the intended behavior. Always check which attribute is modified and whether the method returns the result you expect.

9. Putting it all together: A simple bank account

A bank account demonstrates why instance methods are useful. The account stores a balance, while deposit() and withdraw() provide operations that update it.

Each method uses self to access the current account's balance. The deposit and withdrawal amounts arrive as additional arguments.

This example includes basic validation: deposits must be positive, and withdrawals cannot exceed the current balance. If a validation rule fails, the method raises an exception instead of silently making an invalid change.

This is a teaching example, not a complete financial application. Real financial systems require additional safeguards, such as precise monetary representations and transaction controls.

Implement a basic bank account

Implement a basic bank account
python
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
 
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
 
def withdraw(self, amount):
if amount <= 0:
raise ValueError("Withdrawal must be positive")
if amount > self.balance:
raise ValueError("Insufficient balance")
self.balance -= amount
 
account = BankAccount("Asha", 100)
account.deposit(50)
account.withdraw(30)
print(account.owner)
print(account.balance)
Output
Asha 120

The account starts with a balance of 100 and owner Asha. deposit(50) adds 50, bringing the balance to 150. withdraw(30) subtracts 30, leaving 120. The owner attribute remains Asha. The final balance is 100 + 50 - 30 = 120. Both methods modify the current account through self.balance.

Note

The main pattern is reusable: initialize the object's state, define methods that read or update that state, and validate arguments when necessary.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Forgetting self in an instance method definition.

Why it happens: An instance method definition needs self as its first parameter so the method can access the object on which it is called.

Incorrect Approach
script.py
python
Forgetting self in an instance method definition.
Correct Solution
script.py
python
Include self as the first parameter of a normal instance method so Python can pass the calling instance.

Key takeaway: Include self as the first parameter of a normal instance method so Python can pass the calling instance.

#2 Passing the object explicitly when calling an instance method through it.

Why it happens: When called as object.method(), Python binds the object to self automatically; passing the same object again can shift arguments and cause an error.

Incorrect Approach
script.py
python
Passing the object explicitly when calling an instance method through it.
Correct Solution
script.py
python
Call object.method(arguments). Python supplies the object as self automatically.

Key takeaway: Call object.method(arguments). Python supplies the object as self automatically.

#3 Using a local variable when the intention is to update an attribute.

Why it happens: Assigning to a local variable changes only that local name; assign to self.attribute when the object's stored state should change.

Incorrect Approach
script.py
python
Using a local variable when the intention is to update an attribute.
Correct Solution
script.py
python
Use self.attribute = value or update self.attribute directly when the change must persist on the object.

Key takeaway: Use self.attribute = value or update self.attribute directly when the change must persist on the object.

#4 Assuming a method that uses print() also returns the printed value.

Why it happens: print() displays a value but returns None; use return when callers need the value for later computation.

Incorrect Approach
script.py
python
Assuming a method that uses print() also returns the printed value.
Correct Solution
script.py
python
Use return when the caller needs the result for later calculations, assignments, or conditions.

Key takeaway: Use return when the caller needs the result for later calculations, assignments, or conditions.

#5 Assuming every method call changes the object.

Why it happens: Methods can inspect state without changing it; only operations that assign or mutate state change the object.

Incorrect Approach
script.py
python
Assuming every method call changes the object.
Correct Solution
script.py
python
A method changes state only if its executed code performs a relevant assignment or mutation.

Key takeaway: A method changes state only if its executed code performs a relevant assignment or mutation.

#6 Ignoring invalid arguments that can corrupt an object's state.

Why it happens: Methods that accept invalid values can leave an object in an inconsistent state, so validate inputs before applying updates.

Incorrect Approach
script.py
python
Ignoring invalid arguments that can corrupt an object's state.
Correct Solution
script.py
python
When the operation has requirements, validate its arguments before changing the stored attributes.

Key takeaway: When the operation has requirements, validate its arguments before changing the stored attributes.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is an instance method in Python?
Answer:
An instance method is a function defined inside a class that normally operates on a particular instance. Its first parameter is conventionally named self, and Python supplies the instance when the method is called through an object.
Q2:Why is self used in Python methods?
Answer:
self identifies the current instance. It lets the method read or update that object's attributes, such as self.name or self.balance. It is a convention rather than a reserved keyword.
Q3:How does Python pass self automatically?
Answer:
When an instance method is accessed through an object and called, Python supplies that object as the first argument. Therefore, account.deposit(100) passes account as self and 100 as the deposit amount.
Q4:What is the difference between a local variable and an instance attribute?
Answer:
A local variable is available within its local scope, such as a method body. An instance attribute is stored on the object, typically through self.attribute, and remains available after the method finishes as long as the object remains accessible.
Q5:What is the difference between print() and return in a method?
Answer:
print() displays a value to the output stream. return sends a result to the calling code. A returned value can be assigned to a variable, passed to another function, or used in a calculation. A method that only prints normally returns None.
Q6:Can an instance method modify an object's attributes?
Answer:
Yes. An instance method can assign to self.attribute or update a mutable object stored in an attribute. Such changes affect the current instance and can be observed by subsequent method calls.
Q7:Can one instance method call another instance method?
Answer:
Yes. A method can call another method on the same instance using self.other_method(). For example, increment_twice() can call self.increment() twice to update the same counter.
Q8:What is a common mistake when defining instance methods?
Answer:
A common mistake is omitting self from an ordinary instance method's parameter list. Python still supplies the instance when the method is called through an object, so the call may raise TypeError. Another common mistake is using a local variable instead of updating self.attribute.

Key takeaways

  • An instance method is a function defined inside a class that operates on an instance.
  • self conventionally refers to the current instance.
  • Python supplies self automatically when an instance method is called through an object.
  • Use self.attribute to read or update the current object's state.
  • Additional method parameters receive values supplied by the caller.
  • State changes persist on the object and can affect subsequent method calls.
  • print() displays a value; return provides a result to the caller.
  • A method that finishes without an explicit return value returns None.
  • Methods can call other methods on the same instance using self.method_name().
  • Validate arguments when invalid values could lead to an incorrect object state.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: