Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge | Inheritance
Object-Oriented Programming in Python

book
Challenge

Note

Private methods and attributes of the parent class are not available in the child's class.

The Animal class:

class Animal:
def __init__(self, name = None, age = None):
self.__name = name
self.__age = age

def move(self):
print('Animal is moving...')
1234567
class Animal: def __init__(self, name = None, age = None): self.__name = name self.__age = age def move(self): print('Animal is moving...')
copy
Task

Swipe to start coding

  1. Create a class Cat that inherits the Animal class.
  2. Create the eat method.
  3. Create a 5 kg 10 years old 'Lola' cat.
  4. Move the cat (using the move() method from the Animal class).
  5. 'Feed' the cat (using the eat() method from the Cat class).

Solution

class Animal:
def __init__(self, name = None, age = None):
self.__name = name
self.__age = age
def move(self):
print('Animal is moving...')

# Create a class Cat that inherits the Animal
class Cat(Animal):
def __init__(self, name = None, age = None, weight = 0):
self.__name = name
self.__age = age
# Create the private variable weight
self.__weight = weight
# Create the eat method
def eat(self):
self.__weight += 1
print(f'{self.__name} is {self.__weight} kg now.')

# Create a 10 years old 'Lola' cat
cat = Cat('Lola', 10, 5)
# Use the move() method
cat.move()
# Use the eat() method
cat.eat()

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 2
class Animal:
def __init__(self, name = None, age = None):
self.__name = name
self.__age = age
def move(self):
print('Animal is moving...')

# Create a class Cat that inherits the Animal
___:
def __init__(self, name = None, age = None, weight = 0):
self.__name = name
self.__age = age
# Create the private variable weight
___ = ___
# Create the eat method
___(self):
self.__weight += 1
print(f'{self.__name} is {self.__weight} kg now.')

# Create a 5 kg 10 years old 'Lola' cat
cat = Cat(___)
# Use the move() method
cat.___()
# Use the eat() method
___

Ask AI

expand
ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt