Constructing a Circle From Its Diameter
The initializer of
Circle takes a radius value as an argument and stores it in an instance attribute called
.radius. Then the class implements methods to compute the circle’s area and perimeter using Python’s
The special method
.__repr__() returns a suitable string representation for your class. Save
circle.py in your working directory, and open your Python interpreter and run the code seen on-screen to try out
This looks good. Your class works correctly. Now, let’s say that you also want to instantiate
Circle using the diameter. Then you could use code similar to what’s seen on-screen, but that’s not quite Pythonic or intuitive.
Here, you define
.from_diameter() as a class method. The name follows the popular convention within the Python community using the
from preposition to name constructors that you create as class methods.
The first argument receives a reference to the containing class,
Circle. The second argument holds the diameter of the specific circle that you want to create. Inside the method, you first calculate the radius using the input value of
Then you instantiate
Circle by calling
cls with the radius that results from the
diameter argument. This way, you are in full control of creating and initializing the instances of
Circle using the diameter as an argument.
The call to the
cls argument automatically runs the object creation and initialization steps that Python needs to instantiate a class. Finally,
.from_diameter() returns the new instance to the caller. In this example, you can seemingly achieve the same result by calling
Circle itself instead of
cls. However, this can potentially lead to bugs if your class is subclassed.
Those subclass would then call
Circle instead of themselves when they’re initialized with
.from_diameter(). On-screen, you can see how to use your brand-new constructor to create circles by using the diameter.
Note that the rest of the functionality of
Circle works the same as before. Using the
@classmethod decorator as you did here is the most common way to provide explicit multiple constructors in your classes. With this technique, you have the option to select the right name for each alternative constructor that you provide, which can make your code more readable and maintainable.
Become a Member to join the conversation.