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

book
Challenge

Compito

Swipe to start coding

  1. Create the Cat class:
  • Set info and make_sound methods inside the Cat class;
  • Inside the make_sound method print 'Meow'.
  1. Create the Dog class:
  • Set info and make_sound methods inside the Dog class;
  • Inside the make_sound method print 'Bark'.
  1. Create cat and dog objects based on the Cat and Dog classes respectively.

Soluzione

# Create the Cat class
class Cat:
def __init__(self, name, age):
self.name = name
self.age = age

# Set the info method
def info(self):
print('I am a cat. My name is', self.name, 'I am', self.age, 'years old')
# Set the make_sound method
def make_sound(self):
# Print 'Meow'
print('Meow')

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

# Set the info method
def info(self):
print('I am a dog. My name is', self.name, 'I am', self.age, 'years old')
# Set the make_sound method
def make_sound(self):
# Print 'Bark'
print('Bark')

# Create the cat object
cat = Cat('Kitty', 2)
cat.info()
cat.make_sound()
# Create the dog object
dog = Dog('Fluffy', 4)
dog.info()
dog.make_sound()

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 4. Capitolo 2
single

single

# Create the Cat class
class ___:
def __init__(self, name, age):
self.name = name
self.age = age
# Set the info method
___(self):
print('I am a cat. My name is', self.name, 'I am', self.age, 'years old')
# Set the make_sound method
___(self):
# Print 'Meow'
___('___')
___:
def __init__(self, name, age):
self.name = name
self.age = age
# Set the info method
___
print('I am a dog. My name is', self.name, 'I am', self.age, 'years old')
# Set the make_sound method
___
# Print 'Bark'
___

# Create the cat object
___ = ___('Kitty', 2)
cat.info()
cat.make_sound()
# Create the dog object
___'Fluffy', 4)
dog.info()
dog.make_sound()

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

some-alt