0
0
Pythonprogramming~20 mins

Creating objects in Python - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Object 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 creating an object?
Consider this class and object creation code. What will be printed when running it?
Python
class Car:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

my_car = Car('Toyota', 2020)
print(my_car.brand, my_car.year)
Abrand year
BCar object at memory address
CError: attribute not found
DToyota 2020
Attempts:
2 left
💡 Hint
Look at how the __init__ method assigns values to self.brand and self.year.
Predict Output
intermediate
2:00remaining
What is the output of this code creating multiple objects?
This code creates two objects from the Person class. What will it print?
Python
class Person:
    def __init__(self, name):
        self.name = name

p1 = Person('Alice')
p2 = Person('Bob')
print(p1.name, p2.name)
AError: name attribute missing
BBob Alice
CAlice Bob
DPerson Person
Attempts:
2 left
💡 Hint
Each object has its own name attribute set during creation.
🔧 Debug
advanced
2:00remaining
What error does this code raise when creating an object?
This code tries to create an object but has a mistake. What error will it raise?
Python
class Animal:
    def __init__(self, species):
        self.species = species

pet = Animal()
ATypeError: __init__() missing 1 required positional argument: 'species'
BAttributeError: 'Animal' object has no attribute 'species'
CNameError: name 'Animal' is not defined
DNo error, pet.species is None
Attempts:
2 left
💡 Hint
Check if the constructor requires any arguments and if they are provided.
Predict Output
advanced
2:00remaining
What is the output of this code using a method in an object?
This code defines a class with a method. What will it print when calling greet()?
Python
class Greeter:
    def __init__(self, name):
        self.name = name
    def greet(self):
        return f'Hello, {self.name}!'

g = Greeter('Sam')
print(g.greet())
Agreet
BHello, Sam!
CHello, name!
DError: greet() missing 1 required positional argument
Attempts:
2 left
💡 Hint
The greet method returns a greeting string using the object's name attribute.
🧠 Conceptual
expert
2:00remaining
How many objects are created after running this code?
Consider this code snippet. How many distinct objects are created in memory?
Python
class Box:
    def __init__(self, content):
        self.content = content

b1 = Box('apple')
b2 = Box('banana')
b3 = b1
b4 = Box('apple')
A3
B4
C2
D1
Attempts:
2 left
💡 Hint
Remember that assigning b3 = b1 does not create a new object.