Python Static Methods
A static method in Python is a method that belongs to a class rather than the instance. It doesn't access or modify the class state or instance state. You define it using @staticmethod
decorator.
Static method Python में ऐसा method होता है जो न तो class और न ही object की properties को directly access करता है। इसे @staticmethod
decorator से बनाया जाता है।
Example 1: Basic Static Method
class Employee:
@staticmethod
def company_info():
print("LiveCodeProgramming Pvt. Ltd.")
Employee.company_info()
Output:
LiveCodeProgramming Pvt. Ltd.
The static method company_info()
does not use self or cls. It can be called using class name.
यह static method class की जानकारी देता है और इसे object बनाए बिना call किया जा सकता है।
Example 2: Utility Static Method
class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
@staticmethod
def is_valid_age(age):
return 18 <= age <= 60
print(Employee.is_valid_age(25))
Output:
True
Here, is_valid_age()
is a utility method that checks if age is valid. No need of object-specific data.
यह method age check करता है और किसी object की जरूरत नहीं होती।
Example 3: Use in Constructor
class Employee:
def __init__(self, name, age, salary):
if not Employee.is_valid_age(age):
raise ValueError("Invalid age")
self.name = name
self.age = age
self.salary = salary
@staticmethod
def is_valid_age(age):
return 18 <= age <= 60
e1 = Employee("Aryan", 20, 50000)
print(e1.name, e1.age)
Output:
Aryan 20
Static methods are great for validations or utility functions that are not dependent on instance data.
Static methods validations के लिए बहुत उपयोगी होते हैं जैसे age check करना।