0
0
Pythonprogramming~5 mins

Instance methods in Python

Choose your learning style9 modes available
Introduction

Instance methods let objects do things using their own data. They help objects act on their own information.

When you want an object to describe itself, like showing its name or details.
When you want to change or update an object's own data safely.
When you want to perform actions that depend on the object's current state.
When you want to organize code so each object handles its own behavior.
When you want to reuse code by calling methods on different objects.
Syntax
Python
class ClassName:
    def method_name(self, other_parameters):
        # code using self to access instance data
        pass

self is a special name for the object itself. It must be the first parameter in instance methods.

You call instance methods on objects, not on the class directly.

Examples
A simple instance method that makes a dog bark.
Python
class Dog:
    def bark(self):
        print('Woof!')
Instance method greet uses the dog's own name to say hello.
Python
class Dog:
    def __init__(self, name):
        self.name = name
    def greet(self):
        print(f'Hello, I am {self.name}')
Instance methods to change and show the object's own count value.
Python
class Counter:
    def __init__(self):
        self.count = 0
    def increment(self):
        self.count += 1
    def show(self):
        print(f'Count is {self.count}')
Sample Program

This program creates a Person object with a name and age. It uses instance methods to introduce the person and celebrate a birthday by increasing the age.

Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def introduce(self):
        print(f'Hi, I am {self.name} and I am {self.age} years old.')
    def have_birthday(self):
        self.age += 1
        print(f'Happy birthday {self.name}! You are now {self.age}.')

p = Person('Alice', 30)
p.introduce()
p.have_birthday()
p.introduce()
OutputSuccess
Important Notes

Always include self as the first parameter in instance methods to access the object's data.

Instance methods can change the object's data or just use it to do something.

You call instance methods using the object name, like obj.method().

Summary

Instance methods let objects use and change their own data.

They always have self as the first parameter.

Call them on objects to make the object do something.