I've been looking at Python for a year or two, but I haven't got duck typing in my head. I thought of a way to understand.
By the way, Maybe it's because of the textbook I'm using that I don't have in my head. A little dissed article ↓.
Good book "Introduction to Python3", N selections where explanations have failed (N = 3).
it's simple. There are two steps.
Step 1, write the code for an example that you think is duck typing.
Below is the code I wrote. If you can add a minus to the score, -60 (minus 60 points).
sales point,
Why did you write this code? That's because I remembered that duck typing was a matter of course without any features.
class Tori():#bird
def tobe(self):
print("bata-bata")
def nake(self):
print("ga-ga")
class Duck(Tori):#Duck
def nake(self):
print("ga-ga-ga-ga-ga-ga")
class Ahiru(Tori):#duck
def tobe(self):
print("bata-bata-bata-bata-bata")
duck_1go = Duck()
duck_1go.nake()
duck_1go.tobe()
ahiru_1go = Ahiru()
ahiru_1go.nake()
ahiru_1go.tobe()
Step 2, check the correct answer. I wasn't sure, so I asked the wiki for the correct answer.
https://ja.wikipedia.org/wiki/%E3%83%80%E3%83%83%E3%82%AF%E3%83%BB%E3%82%BF%E3%82%A4%E3%83%94%E3%83%B3%E3%82%B0
There was a ruby code example on the wiki. I rewrote it to python.
def test(foo):
foo.sound()
class Duck():
def sound(self):
print('quack')
class Cat():
def sound(self):
print('myaa')
duck_san = Duck()
cat_san = Cat()
test(duck_san)
test(cat_san)
A supplementary explanation for the code on the wiki is one line below.
** Notice that the two classes have no inheritance relationship. ** **
You can't think of it just by reading a textbook. If you have any comments, please let us know.
Originally, the background and action of this duck typing is meaningful, but after deepening my understanding. .. ..
Recommended Posts