0
0
Pythonprogramming~20 mins

Instance attributes in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Instance Attribute Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of instance attribute modification
What is the output of this Python code involving instance attributes?
Python
class Dog:
    def __init__(self, name):
        self.name = name

d1 = Dog('Buddy')
d2 = Dog('Max')
d1.name = 'Charlie'
print(d2.name)
AMax
BCharlie
CNone
DBuddy
Attempts:
2 left
💡 Hint
Each instance has its own attributes. Changing one does not affect the other.
Predict Output
intermediate
2:00remaining
Instance attribute shadowing class attribute
What will be printed by this code?
Python
class Cat:
    species = 'Felis'

    def __init__(self, name):
        self.name = name

c = Cat('Whiskers')
c.species = 'Panthera'
print(Cat.species)
print(c.species)
APanthera\nPanthera
BFelis\nPanthera
CFelis\nFelis
DPanthera\nFelis
Attempts:
2 left
💡 Hint
Instance attribute with the same name hides the class attribute for that instance.
🔧 Debug
advanced
2:00remaining
Identify the error in instance attribute assignment
What error does this code raise when run?
Python
class Person:
    def __init__(self, name):
        name = name

p = Person('Alice')
print(p.name)
ATypeError
BNameError
CNone (prints 'Alice')
DAttributeError
Attempts:
2 left
💡 Hint
Check if the instance attribute is properly assigned inside __init__.
Predict Output
advanced
2:00remaining
Instance attribute default value behavior
What is the output of this code?
Python
class Counter:
    def __init__(self):
        if not hasattr(self, 'count'):
            self.count = 0
    def increment(self):
        self.count += 1

c1 = Counter()
c2 = Counter()
c1.increment()
c1.increment()
c2.increment()
print(c1.count, c2.count)
A2 1
B1 1
C0 0
D2 2
Attempts:
2 left
💡 Hint
Each instance has its own 'count' attribute initialized to 0.
🧠 Conceptual
expert
2:00remaining
Understanding instance attribute creation timing
When is an instance attribute created in Python classes?
AWhen the attribute is accessed for the first time
BWhen the class is defined
CWhen the instance is created and the attribute is assigned
DWhen the interpreter starts
Attempts:
2 left
💡 Hint
Think about when the attribute actually appears on the object.