Class methods are methods that are called on the class itself, not on a specific object instance. Therefore, it belongs to a class level, and all class instances share a class method. A class method is bound to the class and not the object of the class. It can access only class variables. It can modify the class state by changing the value of a class variable that would apply across all the class objects.
You can also use @classmethod decorator for class method definition.
Syntax Python Class Method:
@classmethod
def fun(cls, arg1, arg2, ...):
Class methods can be called by both class and object. These methods can be called with a class or with an object.
class Cat: |
class Car: brands = list() def __init__(self): Car.brands.append(self) @classmethod def count(cls): return len(Car.brands) c1 = Car() c2 = Car() c3 = Car() print(Car.count()) |
class Employee: emp = [] def __init__(self, name, department): self.name = name self.department = department Employee.emp.append(self) @classmethod def count(cls): return len(Employee.emp) p1 = Employee("Emp1","P") p2 = Employee("Emp2","M") print(Employee.count()) |
@classmethod |
@classmethod the function is also callable without instantiating the class, but its definition follows Subclass, not Parent class, via inheritance, can be overridden by a subclass. That’s because the first argument for @classmethod the function must always be cls (class).
Factory methods are used to create an instance for a class using for example some sort of pre-processing.
We can dynamically delete the class methods from the class. In Python, there are two ways to do it:
By using the del operator
By using delattr() method
The del operator removes the instance method added by class. Use the del class_name.class_method syntax to delete the class method.
Static methods in Python are extremely similar to python class-level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class. staticmethod does not use the state of the object, or even the structure of the class itself. It could be a function external to a class. It is only put inside the class for grouping functions with similar functionality.
Syntax Python Static Method:
class C(object):
@staticmethod
def show(arg1, arg2, ...):
import time class Time: |
class Book: |
We generally use the class method to create factory methods. Factory methods return class objects for different use cases. We generally use static methods to create utility functions.