class animals():
def __init__(self,name,height):
self.name= name
self.height=height
def legs(no_legs):
print("legs: ",no_legs)
animals.legs=staticmethod(animals.legs)
animals.legs(4)
Output
legs : 4
A static method doesn't access or modify the class state, while a class method works with the class itself:
class Sample:
@staticmethod
def static_method():
print("No class data used.")
@classmethod
def class_method(cls):
print("Class data can be used here.")
Static methods are useful for grouping utility functions that don't need access to instance variables:
class MathOperations:
@staticmethod
def add(x, y):
return x + y
print(MathOperations.add(5, 10)) # Output: 15
Static methods are great for utility tasks like validation:
class Validator:
@staticmethod
def is_valid_age(age):
return 0 < age < 120
print(Validator.is_valid_age(25)) # Output: True
Static methods can be used to create specific objects without accessing class data:
class AnimalFactory:
@staticmethod
def create_dog():
return "Dog created"
print(AnimalFactory.create_dog()) # Output: Dog created