0
0
Pythonprogramming~5 mins

Default values in constructors in Python

Choose your learning style9 modes available
Introduction
Default values in constructors let you create objects even if you don't provide all details. This makes your code easier and faster to use.
When you want to create an object but don't have all information ready.
When some details usually stay the same, so you don't want to type them every time.
When you want to make your class flexible for different uses without writing many versions.
When you want to avoid errors from missing values during object creation.
Syntax
Python
class ClassName:
    def __init__(self, param1, param2=default2):
        self.param1 = param1
        self.param2 = param2
Default values are set using = after the parameter name in the constructor.
Parameters with default values should come after parameters without defaults.
Examples
This class Car has default color 'red' and wheels 4 if no values are given.
Python
class Car:
    def __init__(self, color='red', wheels=4):
        self.color = color
        self.wheels = wheels
Here, name must be given but age defaults to 30 if not provided.
Python
class Person:
    def __init__(self, name, age=30):
        self.name = name
        self.age = age
Sample Program
We create two books. The first uses the default author 'Unknown'. The second gives a specific author.
Python
class Book:
    def __init__(self, title, author='Unknown'):
        self.title = title
        self.author = author

book1 = Book('Python Basics')
book2 = Book('Learn AI', 'Alice')

print(f"{book1.title} by {book1.author}")
print(f"{book2.title} by {book2.author}")
OutputSuccess
Important Notes
If you give a value when creating the object, it replaces the default.
Default values can be any type: numbers, strings, lists, or even other objects.
Be careful with mutable default values like lists; they can cause unexpected behavior.
Summary
Default values in constructors make object creation easier and more flexible.
You set defaults by assigning values in the __init__ method parameters.
Use defaults to avoid repeating common values and to handle missing information gracefully.