0
0
Pythonprogramming~20 mins

Purpose of constructors in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Constructor Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Python code using a constructor?
Consider this Python class with a constructor. What will be printed when the code runs?
Python
class Dog:
    def __init__(self, name):
        self.name = name

my_dog = Dog("Buddy")
print(my_dog.name)
ABuddy
BDog object
CNone
DError: missing argument
Attempts:
2 left
💡 Hint
The constructor sets the name attribute when the object is created.
🧠 Conceptual
intermediate
1:30remaining
What is the main purpose of a constructor in Python?
Choose the best description of what a constructor does in a Python class.
AIt initializes new objects with default or given values.
BIt deletes objects when they are no longer needed.
CIt defines methods that can be called on objects.
DIt creates new classes from existing ones.
Attempts:
2 left
💡 Hint
Think about what happens when you create a new object from a class.
Predict Output
advanced
2:00remaining
What will this code print regarding constructor behavior?
Look at this Python code with a constructor and a method. What is the output?
Python
class Car:
    def __init__(self, brand):
        self.brand = brand

    def show_brand(self):
        print(f"Brand: {self.brand}")

car1 = Car("Toyota")
car1.show_brand()
AError: show_brand missing argument
BBrand: car1
CBrand: None
DBrand: Toyota
Attempts:
2 left
💡 Hint
The constructor sets the brand attribute, which the method prints.
🧠 Conceptual
advanced
1:30remaining
Which statement about constructors is true?
Select the true statement about constructors in Python classes.
AConstructors can have any name you choose.
BConstructors run automatically when an object is created.
CConstructors must return a value.
DConstructors can only have one parameter.
Attempts:
2 left
💡 Hint
Think about when the __init__ method runs.
Predict Output
expert
2:00remaining
What is the output of this Python code with multiple constructors?
Python does not support multiple constructors by default. What will happen when this code runs?
Python
class Book:
    def __init__(self, title):
        self.title = title

    def __init__(self, title, author):
        self.title = title
        self.author = author

b = Book("1984")
print(b.title)
ANone
B1984
CError: missing 1 required positional argument: 'author'
DError: multiple constructors not allowed
Attempts:
2 left
💡 Hint
The second __init__ replaces the first one.