0% found this document useful (0 votes)
12 views

Class and Instance method

A class method in Python is defined with the @classmethod decorator and takes the class itself as the first parameter, allowing it to modify class variables applicable to all instances. It can be called using both the class name and instance name, and is useful for tracking class-level data, such as the number of instances created. In contrast, instance methods operate on instance variables and take 'self' as the first parameter, allowing them to access and modify attributes specific to an object.

Uploaded by

Amit kumar Dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Class and Instance method

A class method in Python is defined with the @classmethod decorator and takes the class itself as the first parameter, allowing it to modify class variables applicable to all instances. It can be called using both the class name and instance name, and is useful for tracking class-level data, such as the number of instances created. In contrast, instance methods operate on instance variables and take 'self' as the first parameter, allowing them to access and modify attributes specific to an object.

Uploaded by

Amit kumar Dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Class Method in Python – Explanation with Examples

What is a Class Method?

A class method in Python is a method that is bound to the class and not the instance of the class. It
takes the class itself (cls) as its first parameter instead of the instance (self). Class methods can
modify class state that applies across all instances of the class.

Class methods are defined using the @classmethod decorator.

How to Define a Class Method?

A class method:

 Is defined using the @classmethod decorator.

 Takes cls as its first parameter (instead of self).

 Can access and modify class variables.

 Can be called using both class name and instance name.

Example 1: Defining and Using a Class Method

class Employee:

company = "Tech Corp" # Class variable

def __init__(self, name, salary):

self.name = name

self.salary = salary

@classmethod

def set_company(cls, new_company):

cls.company = new_company # Modifying class variable

# Calling class method

Employee.set_company("Innovate Ltd")

# Creating instances

emp1 = Employee("Alice", 50000)

emp2 = Employee("Bob", 60000)


# Checking if the company name is updated for all instances

print(emp1.company) # Output: Innovate Ltd

print(emp2.company) # Output: Innovate Ltd

Explanation:

 The set_company method is a class method because it is decorated with @classmethod.

 It modifies the class variable company, which applies to all instances.

Example 3: Using Class Method to Track the Number of Instances

Class methods can also help in tracking data at the class level, like counting the number of instances.

class Counter:

count = 0 # Class variable

def __init__(self):

Counter.count += 1 # Increment counter on object creation

@classmethod

def get_count(cls):

return cls.count # Return total count

# Creating instances

obj1 = Counter()

obj2 = Counter()

obj3 = Counter()

# Getting count using class method

print(Counter.get_count()) # Output: 3

🔹 Explanation:

 The get_count method is a class method that returns the total number of instances created.

 Every time a new instance is created, the count variable is incremented.


Instance Methods in Python

An instance method is a method that is defined inside a class and operates on instance
variables (attributes) of an object. It takes self as the first parameter, which refers to the
specific instance of the class.

Key Points About Instance Methods

1. Instance methods can access and modify instance attributes.

2. They are called using an object (instance) of the class.

3. The first parameter of an instance method is always self, which represents the instance itself.

Example: Instance Method in Python

class Person:

def __init__(self, name, age):

self.name = name # Instance variable

self.age = age # Instance variable

def display_info(self): # Instance method

print(f"Name: {self.name}, Age: {self.age}")

# Creating an instance (object) of the Person class

p1 = Person("Alice", 25)

p2 = Person("Bob", 30)

# Calling the instance method

p1.display_info() # Output: Name: Alice, Age: 25

p2.display_info() # Output: Name: Bob, Age: 30

Explanation:

1. __init__() is the constructor that initializes the instance variables (name and age).

2. display_info() is an instance method that prints the name and age of the object.

3. We create two objects: p1 and p2 and call display_info() on each.


Instance Method Modifying Instance Variables

class Car:

def __init__(self, brand, speed):

self.brand = brand

self.speed = speed

def increase_speed(self, increment): # Instance method

self.speed += increment

print(f"{self.brand} speed increased to {self.speed} km/h")

# Creating object

car1 = Car("Toyota", 60)

# Calling instance method

car1.increase_speed(20) # Output: Toyota speed increased to 80 km/h

You might also like