0
0
Pythonprogramming~5 mins

Constructor parameters in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a constructor in Python?
A constructor is a special method named __init__ that runs automatically when you create a new object from a class. It sets up the object’s initial state.
Click to reveal answer
beginner
How do constructor parameters help when creating an object?
Constructor parameters let you give values to the object right when you create it. This way, each object can start with its own unique data.
Click to reveal answer
beginner
What does this code do?<br><pre>class Car:
    def __init__(self, color):
        self.color = color

my_car = Car('red')</pre>
This code defines a class Car with a constructor that takes a color parameter. When my_car is created, it sets its color to 'red'.
Click to reveal answer
intermediate
Can constructor parameters have default values? How?
Yes! You can give constructor parameters default values by assigning them in the __init__ method, like def __init__(self, color='blue'):. If no value is given, the default is used.
Click to reveal answer
beginner
Why do we use self in constructor parameters?
self represents the object being created. It lets us store the parameter values inside the object so they can be used later.
Click to reveal answer
What is the name of the constructor method in Python?
A__start__
B__init__
Cconstructor
Dinit
What does the self parameter represent in a constructor?
AThe object being created
BThe class itself
CA global variable
DA function parameter unrelated to the object
How can you give a constructor parameter a default value?
ABy calling a separate method
BBy setting it outside the class
CBy using a global variable
DBy assigning a value in the parameter list, e.g., <code>def __init__(self, x=5):</code>
What happens if you create an object without passing a required constructor parameter?
APython raises an error
BThe object is created with default values
CThe parameter is set to None automatically
DThe program ignores the missing parameter
Why do we assign constructor parameters to self attributes?
ATo make the parameters global
BTo delete the parameters after use
CTo save the values inside the object for later use
DTo print the values immediately
Explain what constructor parameters are and why they are useful.
Think about how you give information to a new object when you create it.
You got /4 concepts.
    Describe the role of self in a constructor and how it relates to parameters.
    Consider how the object keeps its own information.
    You got /4 concepts.