Instance method in Python
An instance method is a function defined inside a class that operates on the instance (object) of that class. By default, it takes self as the first parameter, which refers to the current object (instance) of the class, allowing it to access and modify instance variables (object’s data) and call other methods of that object.
Syntax
class ClassName:
def instance_method(self, parameters):
# code here
# we can access instance variables using self.variable_name Example: Simple Instance Method.
Python
class Student:
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
# Instance Method
def display_info(self):
# Access instance variables using self
print(f"Name: {self.name}, Age: {self.age}")
# Create an object (instance) of Student
student1 = Student("Ashish", 29)
# Call instance method
student1.display_info() Output: Name: Ashish, Age: 29
Example: Simple Instance Method.
Python
class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
self.balance = balance
# Instance method to deposit money
def deposit(self, amount):
self.balance += amount
print(f"{amount} deposited. New Balance: {self.balance}")
# Instance method to withdraw money
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
print(f"{amount} withdrawn. Remaining Balance: {self.balance}")
else:
print("Insufficient Balance")
# Create object (instance)
account1 = BankAccount("Ashish", 1000)
# Call instance methods
account1.deposit(500)
account1.withdraw(300)
account1.withdraw(2000) # insufficient balance Output: 500 deposited. New Balance: 1500
300 withdrawn. Remaining Balance: 1200
Insufficient Balance
Key Points about Instance Methods:
- Require an object to be called (object.method()).
- Automatically receive self as the first argument.
- Can access or modify instance variables.
- Can call other instance methods inside the class.