Class and Instance method
Class and Instance 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.
A class method:
class Employee:
self.name = name
self.salary = salary
@classmethod
Employee.set_company("Innovate Ltd")
# Creating instances
Explanation:
Class methods can also help in tracking data at the class level, like counting the number of instances.
class Counter:
def __init__(self):
@classmethod
def get_count(cls):
# Creating instances
obj1 = Counter()
obj2 = Counter()
obj3 = Counter()
print(Counter.get_count()) # Output: 3
🔹 Explanation:
The get_count method is a class method that returns the total number of instances created.
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.
3. The first parameter of an instance method is always self, which represents the instance itself.
class Person:
p1 = Person("Alice", 25)
p2 = Person("Bob", 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.
class Car:
self.brand = brand
self.speed = speed
self.speed += increment
# Creating object