[PYTHON] About polymorphism for nesting

Thoughts on polymorphism

Polymorphism without eval can simplify the description of branches, but it cannot eliminate it. Eval can be used to eliminate branch nesting, but it's scary → Oh, I can't instantiate it with python's eval (I'll check it soon)

Commentary

Polymorphism for eliminating general branching seems to cause branching at the time of object creation. When polymorphism is applied, the description of branching becomes lighter, so it is possible to argue that the original purpose of improving maintainability has been achieved, but the effect cannot be realized. There is an idea to do something like eval at the time of object creation in order to completely break the branch, but I am vaguely anxious about eval. I would like to hear your opinions about this area. The following is polymorphism or duck typing, but the same thing is said.

Before polymorphism

switch.py


#There is a branch in the first place
request = param #param contains the parameters in the request and the assumed Dog and Cat
if request == "Dog":
  print "wan"
elif request == "Cat":
  print "nya-"

After polymorphism

polymorphism.py


#There is a branch at the time of object creation
class Dog:
  def foo(self):
    print "wan"
class Cat:
  def foo(self):
    print "nya-"

def make(animal):
  if animal == "Dog":
    return Dog()
  elif animal == "Cat":
    return Cat()

request = param #param contains the parameters in the request and the assumed Dog and Cat
animal = make(request)
animal.foo()

Eval eliminates nesting of polymorphized things

polymorphism_eval.py


#No branch
class Dog:
  def foo(self):
    print "wan"
class Cat:
  def foo(self):
    print "nya-"

request = param #param contains the parameters in the request and the assumed Dog and Cat
animal = eval(request+"()")
animal.foo()

Recommended Posts

About polymorphism for nesting
About Python for loops
About Python, for ~ (range)
About pgbench for MySQL
About Fabric's support for Python 3
About "for _ in range ():" in python
About Japanese fonts of matplotlib (for Mac)
About data expansion processing for deep learning