0
0
Pythonprogramming~20 mins

Classes and objects in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of Classes and Objects
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of method call with class and instance variables
What is the output of this Python code?
Python
class Car:
    wheels = 4
    def __init__(self, color):
        self.color = color

car1 = Car('red')
car2 = Car('blue')
car1.wheels = 3
print(car1.wheels, car2.wheels)
A3 4
B4 3
C3 3
D4 4
Attempts:
2 left
💡 Hint
Remember that instance variables override class variables for that instance only.
Predict Output
intermediate
2:00remaining
Output of method modifying instance variable
What will be printed after running this code?
Python
class Counter:
    def __init__(self):
        self.count = 0
    def increment(self):
        self.count += 1

c = Counter()
c.increment()
c.increment()
print(c.count)
AError
B1
C0
D2
Attempts:
2 left
💡 Hint
Each call to increment adds 1 to count.
Predict Output
advanced
2:00remaining
Output of class method and static method
What is the output of this code?
Python
class Example:
    @classmethod
    def class_method(cls):
        return 'class method called'

    @staticmethod
    def static_method():
        return 'static method called'

print(Example.class_method())
print(Example.static_method())
Astatic method called\nclass method called
Bclass method called\nstatic method called
CError at class_method call
DError at static_method call
Attempts:
2 left
💡 Hint
Class methods receive the class as first argument, static methods do not receive any implicit argument.
Predict Output
advanced
2:00remaining
Output of inheritance and method overriding
What will this code print?
Python
class Animal:
    def speak(self):
        return 'Animal sound'

class Dog(Animal):
    def speak(self):
        return 'Woof'

class Cat(Animal):
    pass

print(Dog().speak())
print(Cat().speak())
AAnimal sound\nAnimal sound
BError
CWoof\nAnimal sound
DWoof\nWoof
Attempts:
2 left
💡 Hint
Dog overrides speak, Cat uses the inherited method.
🧠 Conceptual
expert
2:00remaining
What error does this code raise?
What error will this code raise when run?
Python
class Person:
    def __init__(self, name):
        self.name = name

p = Person()
print(p.name)
ATypeError: __init__() missing 1 required positional argument: 'name'
BAttributeError: 'Person' object has no attribute 'name'
CNameError: name 'Person' is not defined
DNo error, prints None
Attempts:
2 left
💡 Hint
Check how the constructor is called and what arguments it requires.