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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is an instance method in Python?
Q2:Why is self used in Python methods?
Q3:How does Python pass self automatically?
Q4:What is the difference between a local variable and an instance attribute?
Q5:What is the difference between print() and return in a method?
Q6:Can an instance method modify an object's attributes?
Q7:Can one instance method call another instance method?
Q8:What is a common mistake when defining instance methods?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: