#๐Ÿ”’ polymorphism

10 messages ยท Page 1 of 1 (latest)

dire saddle
#

can someone explain how this is an example of polymorphism? other than the repetition of the speak method, i really dont understand how this illustrates polymorphism:

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

    def speak(self):
        return self.name+' says Woof!'

class Cat:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return self.name+' says Meow!'

niko = Dog('Niko')
felix = Cat('Felix')

print(niko.speak())
print(felix.speak())
lunar citrusBOT
#

@dire saddle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

dire saddle
#

!e

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

    def speak(self):
        return self.name+' says Woof!'

class Cat:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return self.name+' says Meow!'

niko = Dog('Niko')
felix = Cat('Felix')

print(niko.speak())
print(felix.speak())
lunar citrusBOT
#

@dire saddle :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | Niko says Woof!
002 | Felix says Meow!
vast shard
#

this is a case of "duck typing".
Both classes are not really related to each other, but the have the same "protocol".
the term "polymorphism" has different forms, and i think duck typing is just one kind of polymorphism.

tender timber
#

This example alone doesn't illustrate much. You could note, though, that both of these classes match a protocol like

class Speaks(Protocol):
    def speak(self) -> str: ...
dire saddle
#

polymorphism is the process of reusing the same method accross different class right?

#

or am i misunderstanding this

lunar citrusBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.