0
0
Pythonprogramming~5 mins

Default values in constructors in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a constructor in Python classes?
A constructor is a special method named __init__ that runs when you create a new object from a class. It sets up the object’s initial state.
Click to reveal answer
beginner
How do you set a default value for a constructor parameter in Python?
You assign a value to the parameter in the __init__ method like def __init__(self, name='Guest'):. If no argument is given, the default is used.
Click to reveal answer
beginner
Why use default values in constructors?
Default values let you create objects without giving all details every time. This makes your code simpler and more flexible.
Click to reveal answer
beginner
What happens if you call a constructor without a parameter that has a default value?
The constructor uses the default value for that parameter automatically.
Click to reveal answer
beginner
Show a simple example of a Python class with a constructor that has a default value.
Example:<br><pre>class Person:
    def __init__(self, name='Guest'):
        self.name = name

p1 = Person()
print(p1.name)  # Output: Guest

p2 = Person('Alice')
print(p2.name)  # Output: Alice</pre>
Click to reveal answer
What is the purpose of a default value in a constructor parameter?
ATo make the constructor private
BTo provide a value if no argument is passed
CTo force the user to pass a value
DTo delete the parameter
How do you define a default value for a parameter in Python's __init__ method?
Adef __init__(self, param=default):
Bdef __init__(self, param): param = default
Cdef __init__(self, param): return default
Ddef __init__(self, param?=default):
What will print(p.name) output if p = Person() and def __init__(self, name='Guest')?
AError
BNone
CGuest
DEmpty string
Can you have multiple parameters with default values in a constructor?
ADefaults are not allowed in constructors
BNo, only one parameter can have a default
COnly the first parameter can have a default
DYes, all can have defaults
What happens if you call Person('Bob') when def __init__(self, name='Guest')?
AThe name 'Bob' is used instead of the default
BThe default 'Guest' is used anyway
CAn error occurs
DThe constructor ignores the argument
Explain how default values in constructors help when creating objects.
Think about what happens if you don't pass some values when making an object.
You got /4 concepts.
    Write a simple Python class with a constructor that has two parameters, one with a default value.
    Use <code>def __init__(self, param1, param2=default):</code> format.
    You got /4 concepts.