Set Default Values for Properties in Class in Python

Set Default Values for Properties in Class

We can set default values for properties in the class definition, either by assigning the properties with the default values inside the class, or by specifying optional arguments in __init__() function definition.

In this tutorial, we shall go through these two methods and learn how to set default values for properties in a class definition.

1. Assign properties with default values

In the following program, we have Person class with two properties: name, age. We assign default values for these properties name and age with NA and 0 respectively.

First we create an object person1 of type Person, and print the details. Since, we have not set the properties of this object with values, the default values would be assigned, and the same would be printed out when we call printDetails() function on the object.

Then, we shall set the name and age properties for person1 with Mike and 21 respectively. And call printDetails() function on the person1 object.

Python Program

class Person:
    name="NA"
    age="0"

    def printDetails(self):
        print("\nPerson Details")
        print("Name :", self.name)
        print("Age  :", self.age)

person1 = Person()
person1.printDetails()

person1.name = "Mike"
person1.age = 21
person1.printDetails()
Run Code Copy

Output

Person Details
Name : NA
Age  : 0

Person Details
Name : Mike
Age  : 21

2. Use named parameters in __init()__ function

As we already mentioned, we can use named parameters in __init__() function definition to set default value for the properties.

In the following program, we have Person class with two properties: name, age.

We define __init__() function in the Person class with the named parameters: name and age.

Python Program

class Person:
    def __init__(self, name="NA", age="0"):
        self.name = name
        self.age = age

    def printDetails(self):
        print("\nPerson Details")
        print("Name :", self.name)
        print("Age  :", self.age)

person1 = Person()
person1.printDetails()

person1.name = "Mike"
person1.age = 21
person1.printDetails()
Run Code Copy

Output

Person Details
Name : NA
Age  : 0

Person Details
Name : Mike
Age  : 21

Summary

In this Python Classes and Objects tutorial, we learned how to set default values for properties of a class object.

Code copied to clipboard successfully 👍