0
0
Pythonprogramming~20 mins

Class attributes in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Class Attribute Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of class attribute access
What is the output of this code?
Python
class Dog:
    species = "Canis familiaris"

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

dog1 = Dog("Buddy")
dog2 = Dog("Max")
print(dog1.species)
print(dog2.species)
print(Dog.species)
AError: species is not defined
B
Canis familiaris
Canis familiaris
Canis familiaris
C
Canis familiaris
Max
Buddy
D
Buddy
Max
Canis familiaris
Attempts:
2 left
💡 Hint
Class attributes are shared by all instances unless overridden.
Predict Output
intermediate
2:00remaining
Changing class attribute affects instances
What is the output of this code?
Python
class Car:
    wheels = 4

car1 = Car()
car2 = Car()
Car.wheels = 6
print(car1.wheels)
print(car2.wheels)
A
4
4
BError: cannot assign to wheels
C
4
6
D
6
6
Attempts:
2 left
💡 Hint
Changing a class attribute changes it for all instances that don't override it.
Predict Output
advanced
2:00remaining
Instance attribute shadows class attribute
What is the output of this code?
Python
class Book:
    genre = "Fiction"

b1 = Book()
b2 = Book()
b2.genre = "Non-Fiction"
print(b1.genre)
print(b2.genre)
print(Book.genre)
A
Fiction
Fiction
Fiction
B
Non-Fiction
Non-Fiction
Non-Fiction
C
Fiction
Non-Fiction
Fiction
DError: genre attribute missing
Attempts:
2 left
💡 Hint
Instance attributes override class attributes with the same name.
Predict Output
advanced
2:00remaining
Modifying mutable class attribute affects all instances
What is the output of this code?
Python
class Team:
    members = []

team1 = Team()
team2 = Team()
team1.members.append("Alice")
print(team1.members)
print(team2.members)
print(Team.members)
A
['Alice']
['Alice']
['Alice']
B
['Alice']
[]
[]
C
[]
[]
[]
DError: cannot append to members
Attempts:
2 left
💡 Hint
Mutable class attributes are shared by all instances.
🧠 Conceptual
expert
2:30remaining
Class attribute behavior with inheritance
Given this code, what is the output?
Python
class Animal:
    sound = "Generic"

class Cat(Animal):
    pass

class Dog(Animal):
    sound = "Bark"

print(Animal.sound)
print(Cat.sound)
print(Dog.sound)
A
Generic
Generic
Bark
B
Generic
Bark
Bark
C
Generic
Generic
Generic
DError: sound attribute missing in Cat
Attempts:
2 left
💡 Hint
Child classes inherit class attributes unless they override them.