Using @classmethod for Multiple Class Constructors
00:00
Using @classmethod
for Multiple Constructors. A powerful technique for providing multiple constructors in Python is to use the @classmethod
decorator.
00:12
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.
00:23
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.
00:43
DemoClass
defines a class method using Python’s built-in @classmethod
decorator. The first argument of .class_method()
holds the class itself.
00:53
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.
01:17
No matter how you invoke .class_method()
, it will receive DemoClass
as its first argument.
01:26
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.
01:40
The @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.
01:55
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.