Python Class Methods
A class method is a method that works with the class itself rather than instances. It's defined using @classmethod
and takes cls
as the first parameter.
Class method ऐसा method होता है जो class के साथ काम करता है, न कि object के साथ। इसे @classmethod
से define करते हैं और इसका पहला parameter cls
होता है।
Example 1: Basic Class Method
class Employee:
company = "LiveCodeProgramming"
@classmethod
def change_company(cls, new_name):
cls.company = new_name
print(Employee.company)
Employee.change_company("CodeMaster Inc.")
print(Employee.company)
Output:
LiveCodeProgramming CodeMaster Inc.
This method updates class-level data. All instances see the new value.
यह method class variable को update करता है जो सभी objects में shared होता है।
Example 2: Alternative Constructor
class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
@classmethod
def from_string(cls, data_str):
name, age, salary = data_str.split(',')
return cls(name, int(age), int(salary))
emp1 = Employee.from_string("Aryan,24,50000")
print(emp1.name, emp1.age, emp1.salary)
Output:
Aryan 24 50000
Class methods are useful for creating objects from string or other formats.
Class methods का उपयोग object को alternate तरीके से बनाने में होता है जैसे string से।
Example 3: Counting Objects
class Employee:
count = 0
def __init__(self, name):
self.name = name
Employee.count += 1
@classmethod
def total_employees(cls):
return cls.count
e1 = Employee("John")
e2 = Employee("Riya")
print("Total:", Employee.total_employees())
Output:
Total: 2
Use class methods to track and report class-level operations like object count.
Class methods object की संख्या गिनने जैसे कामों के लिए उपयोगी होते हैं।