I created a class in Python and tried duck typing

Judgment by human class and inheritance, car class

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.

Duck typing in Ruby

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.

Duck typing in 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.

Summary

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

I created a class in Python and tried duck typing
I tried playing a typing game in Python
I wrote a class in Python3 and Java
I created a password tool in Python.
I tried adding a Python3 module in C
Python: I tried a liar and an honest tribe
I tried to create a class that can easily serialize Json in Python
I tried [scraping] fashion images and text sentences in Python.
I made a simple typing game with tkinter in Python
Python ABC-Abstract Classes and Duck Typing
I tried to implement a one-dimensional cellular automaton in Python
I created a stacked bar graph with matplotlib in Python and added a data label
I tried "a program that removes duplicate statements in Python"
I tried "How to get a method decorated in Python"
I tried programming the chi-square test in Python and Java.
I tried to make a stopwatch using tkinter in python
I tried Line notification in Python
I also tried to imitate the function monad and State monad with a generator in Python
I tried to make a periodical process with Selenium and Python
I was addicted to confusing class variables and instance variables in Python
I thought a Python class variable was an instance variable and died
Generate a first class collection in Python
I tried to implement PLSA in Python
I tried to implement permutation in Python
I made a payroll program in Python!
I tried to implement PLSA in Python 2
I tried using Bayesian Optimization in Python
I tried to implement ADALINE in Python
I tried a functional language with Python
I tried to implement PPO in Python
Generate a class from a string in Python
A way to understand Python duck typing
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
I tried to develop a Formatter that outputs Python logs in JSON
I tried to create a sample to access Salesforce using Python and Bottle
I tried to implement a card game of playing cards in Python
Organize python modules and packages in a mess
I tried web scraping using python and selenium
A memo that I wrote a quicksort in Python
I tried object detection using Python and OpenCV
I want to create a window in Python
[python] Difference between variables and self. Variables in class
I tried simulating the "birthday paradox" in Python
I tried the least squares method in Python
A memo created in a package and registered in PyPI
I tried Jacobian and partial differential with python
I tried to implement TOPIC MODEL in Python
I tried reading a CSV file using Python
I tried non-blocking I / O Eventlet behavior in Python
I tried running alembic, a Python migration tool
I tried to implement selection sort in python
I made a Caesar cryptographic program in Python.
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
[Python] Created a class to play sin waves in the background with pyaudio
I tried to implement what seems to be a Windows snipping tool in Python
case class in python
I tried Python> autopep8
I tried Python> decorator
Class notation in Python
Draw a graph in Julia ... I tried a little analysis
I tried to graph the packages installed in Python