Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende 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
Tarea

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).

Solución

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()

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 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
___

Pregunte a AI

expand
ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

some-alt