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

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

Lösning

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

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 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
___

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt