There seems to be a duck test. According to Wikipedia's information "If it walks like a duck and quacks like a duck, it must be a duck" "If it walks like a duck and sounds like a duck, it must be a duck." It seems to be the idea. Duck typing came from here.
Duck typing looks like this in Ruby, for example.
sampleRuby.rb
#test
def test(foo)
puts foo.sound
end
#Duck barks
class Duck
def sound
'quack'
end
end
#Meow of a cat
class Cat
def sound
'myaa'
end
end
#Run
test(Duck.new)
test(Cat.new)
The output is
python
#Output result
quack
myaa
In short, it seems that you can use methods with the same name in different classes, and you can switch between the same operations on different objects.
For example, suppose a young man and an adult inherit a human class and judge it in the car class to determine whether they are qualified as drivers. For example, what about the following sample code? Python.
samplePython.py
#
#Human class
# 2020.07.24 ProOJI
#
class Person(object):
"""Age method"""
def __init__(self, age=1):
self.age = age
"""Driver qualification method"""
def drive(self):
if self.age >= 18:
print('You can drive!')
print("Because You're {} years old.".format(self.age))
else:
raise Exception('Sorry...you cannot drive.')
#Youth class
class Young(Person):
def __init__(self, age=12):
if age < 18:
super().__init__(age)
else:
raise ValueError
#Adult class
class Adult(Person):
def __init__(self, age=18):
if age >= 18:
super().__init__(age)
else:
raise ValueError
#
#Car class
#Judgment of driver qualification
class Car(object):
def __init__(self, model=None):
self.model = model
def ride(self, person):
person.drive()
#Youth_Instance generation (13 years old)
young = Young(13)
#grown up_Instance generation (46 years old)
adult = Adult(46)
python
#Automobile_Instance generation_1
car = Car()
#Judgment of young people 13 years old
car.ride(young)
#Output result
# Exception: Sorry...you cannot drive.
python
#Automobile_Instance generation_2
car = Car()
#Judgment of young people 46 years old
car.ride(adult)
#Output result
# You can drive!
# Because You're 46 years old.
There is a concept of polymorphism in programming, and in Japanese it is called polymorphism and diversity. This is one of the object-oriented concepts. You can use methods with the same name, even if they have different class types, and you can switch between the same operations on different objects. It turns out that such code is called duck typing.
Recommended Posts