Challenge - 5 Problems
Master of Classes and Objects
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Remember that instance variables override class variables for that instance only.
✗ Incorrect
car1 has an instance variable wheels set to 3, so car1.wheels is 3. car2 does not have an instance variable wheels, so it uses the class variable wheels which is 4.
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Each call to increment adds 1 to count.
✗ Incorrect
The increment method adds 1 to the count attribute each time it is called. After two calls, count is 2.
❓ Predict Output
advanced2: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())
Attempts:
2 left
💡 Hint
Class methods receive the class as first argument, static methods do not receive any implicit argument.
✗ Incorrect
Both methods are called on the class. class_method returns 'class method called', static_method returns 'static method called'.
❓ Predict Output
advanced2: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())
Attempts:
2 left
💡 Hint
Dog overrides speak, Cat uses the inherited method.
✗ Incorrect
Dog's speak method returns 'Woof'. Cat does not override speak, so it uses Animal's speak returning 'Animal sound'.
🧠 Conceptual
expert2: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)
Attempts:
2 left
💡 Hint
Check how the constructor is called and what arguments it requires.
✗ Incorrect
The constructor __init__ requires a 'name' argument, but none was given when creating p, so Python raises a TypeError.