0
0
Pythonprogramming~20 mins

Adding custom attributes in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Custom Attribute Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of adding a custom attribute to a class instance?

Consider the following Python code where we add a custom attribute to an instance of a class. What will be printed?

Python
class Car:
    def __init__(self, brand):
        self.brand = brand

my_car = Car('Toyota')
my_car.color = 'red'
print(my_car.color)
AAttributeError
BToyota
Cred
DNone
Attempts:
2 left
💡 Hint

Think about what happens when you add a new attribute directly to an instance.

Predict Output
intermediate
2:00remaining
What happens when you add a custom attribute to a class itself?

Look at this code where a custom attribute is added to the class, not the instance. What will be the output?

Python
class Dog:
    def __init__(self, name):
        self.name = name

Dog.legs = 4
buddy = Dog('Buddy')
print(buddy.legs)
ANone
B4
CAttributeError
D0
Attempts:
2 left
💡 Hint

Remember that instances can access class attributes if they don't have their own.

Predict Output
advanced
2:00remaining
What error occurs when accessing a missing custom attribute?

What error will this code produce when trying to print a missing attribute?

Python
class Book:
    def __init__(self, title):
        self.title = title

novel = Book('1984')
print(novel.author)
AKeyError
BNameError
CTypeError
DAttributeError
Attempts:
2 left
💡 Hint

Think about what happens when you try to access an attribute that was never set.

🧠 Conceptual
advanced
2:00remaining
How to add a custom attribute to all instances of a class after creation?

You want to add a new attribute category to all existing and future instances of a class Product. Which approach works?

AAdd <code>Product.category = 'general'</code> after instances are created
BAdd <code>self.category = 'general'</code> inside <code>__init__</code> method
CAdd <code>product.category = 'general'</code> for each instance separately
DAdd <code>del Product.category</code> after instances are created
Attempts:
2 left
💡 Hint

Think about class attributes and how instances access them.

Predict Output
expert
2:00remaining
What is the output after modifying a custom attribute on one instance?

Given this code, what will be printed?

Python
class Employee:
    department = 'Sales'

emp1 = Employee()
emp2 = Employee()

emp1.department = 'Marketing'
print(emp2.department)
ASales
BMarketing
CAttributeError
DNone
Attempts:
2 left
💡 Hint

Remember the difference between instance and class attributes.