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.
Jump into concepts and practice - no test required
class ClassName: def __init__(self, param1, param2=default2): self.param1 = param1 self.param2 = param2
class Car: def __init__(self, color='red', wheels=4): self.color = color self.wheels = wheels
class Person: def __init__(self, name, age=30): self.name = name self.age = age
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}")
__init__ method)?age in a Python class constructor?age=30.class Person:
def __init__(self, name, age=25):
self.name = name
self.age = age
p = Person('Alice')
print(p.name, p.age)age=25 as a default, so if age is not given, it uses 25.p = Person('Alice') without age, so age is 25. Printing p.name and p.age shows 'Alice 25'.class Car:
def __init__(self, model='Sedan', year):
self.model = model
self.year = yearmodel='Sedan' is a default parameter before year which has no default. This causes a syntax error.Book where the author defaults to 'Unknown' and pages defaults to 100 if not provided. Which constructor is correct?author and pages have default values, so order is flexible. Options B and C have syntax errors.self.author and self.pages inside the constructor body.