Using @classmethod for Multiple Class Constructors
@classmethod for Multiple Constructors. A powerful technique for providing multiple constructors in Python is to use the
This allows you to turn a regular method into a class method. Unlike a regular method, a class method doesn’t take the current instance,
self, as an argument.
Instead, it takes the class itself, which is commonly passed in as the
cls argument. Using
cls to name this argument is a popular convention in the Python community.
00:36 On-screen, you can see the basic syntax to define a class method.
DemoClass defines a class method using Python’s built-in
@classmethod decorator. The first argument of
.class_method() holds the class itself.
Through this argument, you can access the class from inside itself. In this example, you access the
.__name__ attribute, which stores the name of the underlying class as a string.
01:04 It’s important to note that you can access a class method using either the class or a concrete instance of the class at hand.
No matter how you invoke
.class_method(), it will receive
DemoClass as its first argument.
The ultimate reason why you can use class methods as constructors is that you don’t need an instance to call a class method. Using the
@classmethod decorator makes it possible to add as many explicit constructors as you need to a given class.
@classmethod decorator returns the instance of the class. It’s a Pythonic and popular way to implement multiple constructors, and you can also call this type of constructor an alternative constructor.
Now, how can you use a class method to customize Python’s instantiation process? Instead of fine-tuning
.__init__() and the object initialization, you’ll control both steps: object creation and initialization. Through the following examples, you’ll learn how to do just that, starting with an example where you construct a circle from its diameter.
Become a Member to join the conversation.