In Python, the classmethod()
function is used to define a class method. A class method is a method that is bound to the class and not the instance of the class, and can be called on the class itself rather than on an instance of the class. This article will tell you how to define a class method using the @classmethod decorator in python, and how to use class method to implement a single instance class.
1. How To Define Class Method In Python.
- To define a class method using the
classmethod()
function, we need to use the@classmethod
decorator before the method definition. - The method should take the class as its first parameter (usually named
cls
) instead of the instance of the class (usually namedself
). - Here is the syntax for defining a class method using the
classmethod()
function:class MyClass: @classmethod def my_class_method(cls, arg1, arg2, ...): # Method code here
- In the above syntax,
my_class_method
is the name of the class method,cls
is the first parameter that refers to the class itself, andarg1
,arg2
, etc. are the parameters that the method takes.
2. How To Use Python Class Method Examples.
2.1 How to use python classmethod decorator to define a class method.
- The
classmethod
decorator in Python is a built-in decorator that define a function as a class method. - Class methods are methods that are bound to the class and not the instance of the class.
- Class methods can be called on the class itself rather than on an instance of the class.
- Here is an example.
class MyClass: count = 0 def __init__(self): MyClass.count += 1 @classmethod def get_count(cls): return cls.count obj1 = MyClass() obj2 = MyClass() print(MyClass.get_count()) # Output: 2
- In the above example, we define a class
MyClass
with a class variablecount
and a constructor that increments the count variable each time a new instance of the class is created. - We then define a class method
get_count()
using the@classmethod
decorator. - The
get_count()
method returns the value of thecount
variable. - We can call the
get_count()
method on the class itself, rather than on an instance of the class. - The
classmethod
decorator takes a single argument, which is the function that we want to convert to a class method. - The function should take the class as its first parameter (usually named
cls
) instead of the instance of the class (usually namedself
).
2.2 How to create a class method to initialize an instance from a string.
- Below is the example source code.
class MyClass: def __init__(self, x, y): self.x = x self.y = y @classmethod def from_string(cls, string): x, y = map(int, string.split(',')) return cls(x, y) obj = MyClass.from_string('5,10') print(obj.x) # Output: 5 print(obj.y) # Output: 10
- In this example, we define a class
MyClass
with a constructor that takes two parametersx
andy
. - We then define a class method
from_string()
using the@classmethod
decorator. - The
from_string()
method takes a string argument in the format “x,y” and converts it to integers using themap()
function. - It then creates and returns a new instance of the class with the given
x
andy
values. - We can call the
from_string()
method on the class itself, rather than on an instance of the class.
2.3 How to use a class method to create a singleton instance of a class.
- Below is the example source code.
class MySingleton: instance = None def __init__(self): if MySingleton.instance is None: MySingleton.instance = self else: raise Exception("An instance of MySingleton already exists!") @classmethod def get_instance(cls): if cls.instance is None: cls.instance = MySingleton() return cls.instance obj1 = MySingleton.get_instance() obj2 = MySingleton.get_instance() print(obj1 is obj2) # Output: True
- In this example, we define a class
MySingleton
that can have only one instance. - We define a class variable
instance
to keep track of the singleton instance. - We then define a constructor that checks if an instance of the class already exists and raises an exception if it does.
- We define a class method
get_instance()
using the@classmethod
decorator. - The
get_instance()
method checks if the singleton instance already exists and returns it if it does. - If the singleton instance does not exist, it creates a new instance of the class and returns it.
- We can call the
get_instance()
method on the class itself, rather than on an instance of the class.