Optional Arguments for a Class Constructor in Python

Optional Arguments for a Class Constructor in Python

Vaibhav Vaibhav Mar-21, 2022 Dec-28, 2021 Python Python Class

As the name suggests, an optional argument is an argument for which passing a value is not compulsory. For such an argument, a default value is assessed. If some value is passed for such an argument, the new value overwrites the default value.

In this article, we will learn how to set optional arguments for classes in Python.

Set Optional Arguments for a Class Constructor in Python

To add optional arguments to classes in Python, we have to assign some default values to the arguments in the class’s constructor function signature. Adding default values is a straightforward task. We have to equate arguments to their default values like x = 3, name = "Untitled", etc. The default value will be considered if no values are passed for these optional arguments. To following Python code depicts the concept discussed above.

class Point:
    def __init__(self, x, y, z = 0):
        self.x = x
        self.y = y
        self.z = z
    
    def __str__(self):
        return f"X: {self.x}, Y: {self.y}, Z:{self.z}"

print(Point(1, 2)) # Object 1
print(Point(54, 92, 0)) # Object 2
print(Point(99, 26, 100)) # Object 3

Output:

X: 1, Y: 2, Z:0
X: 54, Y: 92, Z:0
X: 99, Y: 26, Z:100

The class Point constructor accepts three arguments: x, y, and z. Here z is the optional argument because it has a default value set for it. This makes the other two arguments, x and y, compulsory. For Object 1, no value was passed for the z argument, and from the output, we can see that the default value was considered for z. And, for Object 3, 100 was passed for the z argument, and from the output, we can see that 100 was considered over the default 0 value.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

Related Article - Python Class

  • Python Generator Class
  • Data Class Inheritance in Python
  • Serialize a Python Class Object to JSON
  • Python Abstract Property
  • Python Class Factory
  • Python Class Equality