Here we are going to discuss about the difference between Class method vs Static method in python and when to use the class method
and static method.
Class method in python:
A class method in python is like a special function that belongs to the class itself,not to any particular object created from the class.
It can access and modify class level variables,and its useful for tasks related to the class as a whole,rather than individual instances
of the class .
Syntax for Class Method:
class C(object): @classmethod def fun(cls,arg1,arg2,....): ..... fun: function that needs to be converted into a class method returns: a class method for function.
class MyClass: def __init__(self, value): self.value = value def get_value(self): return self.value obj = MyClass(20) print(obj.get_value())
output: 20
Static Method in python:
A static method in python is like a regular function inside a class, But it doesn’t access or modify any class or instance variables.
it’s just a function that lives inside the class because it’s related to the class in some way, but it doesn’t depend on any specific
instance of the class. It’s handy for grouping functions together that are related to the class but don’t need to interact with any
specific instance of it .
Syntax for Static Method:
class C(object): @staticmethod def fun(arg1, arg2,...): .... returns: a static method for function fun.
class MyClass: def __init__(self, value): self.value = value @staticmethod def get__max_value(x, y): return max(x, y) obj = MyClass(20) (MyClass.get_max_value(30, 40)) (obj.get_max_value(30, 40))
output: 40 40
Class Method vs Static Method:
The difference between class method and static method
- A class method takes class as the first parameter but in static method needs no
specific parameters. - A class method can access or modify the class but in the case of static method
it cant access or modify it. - We use @classmethod decorator in python to create a class method and
@staticmethod decorator to create a static method in python.from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def fromBirthyear(cls, name, year): return cls(name, date.today().year - year) @staticmethod def isAdult(age): return age > 18 person1 = Person('renusri',21) person2 = Person.fromBirthYear('renusri', 1996) print(person1.age) print(person2.age) print(Person.isAdult(22))
output: 21 25 true