Did you know that you can create instances of a class using different sets of arguments?

Let’s consider a class that makes it possible to create triangle instances based on the lengths of their three sides. In this case, the __init__ method accepts three parameters, one for each side length.

However, a triangle can also be defined in other ways, as shown below: by one side and the two adjacent angles, or by two sides and the angle between them.

So how can you create triangles from these alternative sets of data using the same class?

You can achieve this using class methods. Since a class method has access to the class object itself, it can not only interact with class-level attributes but also instantiate new objects within the method. The return value of such a method can therefore be a new instance of the class. In essence, this allows you to define alternative constructors — commonly referred to as factory methods — which produce instances of the class.

In the following code snippet, you can see a Triangle class that includes two factory methods supporting these alternative ways of creating triangles. The side lengths are calculated using the Law of Sines and the Law of Cosines from trigonometry.

You can read more about class methods in the chapter „Types and classes – implementing types with classes” in the e-book Python Knowledge Building Step by Step.

Interested in the e-book Python Knowledge Building Step by Step: From the Basics to Your First Desktop Application?