0
0
Pythonprogramming~10 mins

Parent and child classes in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a child class that inherits from the parent class.

Python
class Parent:
    def greet(self):
        return "Hello from Parent"

class Child([1]):
    pass
Drag options to blanks, or click blank then click option'
Aobject
BParent
CChild
Dself
Attempts:
3 left
💡 Hint
Common Mistakes
Using the child class name instead of the parent class name in inheritance.
Forgetting to put parentheses after the child class name.
2fill in blank
medium

Complete the code to call the parent class method from the child class.

Python
class Parent:
    def greet(self):
        return "Hello from Parent"

class Child(Parent):
    def greet(self):
        return "Child says: " + [1].greet()
Drag options to blanks, or click blank then click option'
Asuper()
Bself
CParent
DChild
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the method on self which causes recursion.
Calling the method on the child class name instead of the parent.
3fill in blank
hard

Fix the error in the child class constructor to properly call the parent constructor.

Python
class Parent:
    def __init__(self, name):
        self.name = name

class Child(Parent):
    def __init__(self, name, age):
        [1].__init__(self, name)
        self.age = age
Drag options to blanks, or click blank then click option'
Asuper()
BChild
Cself
DParent
Attempts:
3 left
💡 Hint
Common Mistakes
Using self.__init__ which causes infinite recursion.
Using super() without parentheses or incorrectly.
4fill in blank
hard

Fill in the blank to create a child class that overrides a method and calls the parent method inside it.

Python
class Parent:
    def info(self):
        return "Parent info"

class Child(Parent):
    def info(self):
        return [1]().info() + " and Child info"
Drag options to blanks, or click blank then click option'
AParent
Bself
Csuper
DChild
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the method on self which causes recursion.
Calling the method on the child class name instead of the parent.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps child class names to their ages if age is greater than 10.

Python
children = [Child("Anna", 12), Child("Ben", 9), Child("Cara", 15)]
ages = { [1]: [2] for child in children if child.age [3] 10 }
Drag options to blanks, or click blank then click option'
Achild.name
Bchild.age
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong attribute for keys or values.
Using the wrong comparison operator causing wrong filtering.