0
0
Pythonprogramming~20 mins

Inheriting attributes and methods in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Inheritance Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of inherited method call
What is the output of this Python code that uses inheritance?
Python
class Animal:
    def speak(self):
        return "I make a sound"

class Dog(Animal):
    pass

pet = Dog()
print(pet.speak())
AAttributeError
B"Dog barks"
C"I am an animal"
D"I make a sound"
Attempts:
2 left
💡 Hint
The Dog class does not override the speak method.
Predict Output
intermediate
2:00remaining
Value of inherited attribute after modification
What is the value of pet.color after running this code?
Python
class Animal:
    def __init__(self):
        self.color = "brown"

class Dog(Animal):
    def __init__(self):
        super().__init__()
        self.color = "black"

pet = Dog()
A"black"
B"brown"
CNone
DAttributeError
Attempts:
2 left
💡 Hint
The Dog class calls super().__init__() then changes color.
🔧 Debug
advanced
2:00remaining
Identify the error in method overriding
What error does this code raise when executed?
Python
class Animal:
    def speak(self):
        return "sound"

class Dog(Animal):
    def speak():
        return "bark"

pet = Dog()
print(pet.speak())
A"bark"
BAttributeError: 'Dog' object has no attribute 'speak'
CTypeError: speak() missing 1 required positional argument: 'self'
DSyntaxError
Attempts:
2 left
💡 Hint
Check the method signature of speak in Dog.
Predict Output
advanced
2:00remaining
Output of method overriding with super()
What is printed when this code runs?
Python
class Animal:
    def speak(self):
        return "sound"

class Dog(Animal):
    def speak(self):
        return super().speak() + " and bark"

pet = Dog()
print(pet.speak())
A"bark"
B"sound and bark"
C"sound"
DAttributeError
Attempts:
2 left
💡 Hint
super() calls the parent class method.
🧠 Conceptual
expert
2:00remaining
Number of attributes in instance after inheritance and modification
Given the code below, how many attributes does the instance 'pet' have?
Python
class Animal:
    def __init__(self):
        self.legs = 4
        self.color = "brown"

class Dog(Animal):
    def __init__(self):
        super().__init__()
        self.color = "black"
        self.tail = True

pet = Dog()
A3
B2
C4
D1
Attempts:
2 left
💡 Hint
Count all attributes set on pet after Dog.__init__ runs.