<p>你正在寻找一个工厂模式。你知道吗</p>
<p>快速谷歌搜索提供:</p>
<pre><code># Factory/shapefact1/ShapeFactory1.py
# A simple static factory method.
from __future__ import generators
import random
class Shape(object):
# Create based on class name:
def factory(type):
#return eval(type + "()")
if type == "Circle": return Circle()
if type == "Square": return Square()
assert 0, "Bad shape creation: " + type
factory = staticmethod(factory)
class Circle(Shape):
def draw(self): print("Circle.draw")
def erase(self): print("Circle.erase")
class Square(Shape):
def draw(self): print("Square.draw")
def erase(self): print("Square.erase")
# Generate shape name strings:
def shapeNameGen(n):
types = Shape.__subclasses__()
for i in range(n):
yield random.choice(types).__name__
shapes = \
[ Shape.factory(i) for i in shapeNameGen(7)]
for shape in shapes:
shape.draw()
shape.erase()
</code></pre>
<p>给<a href="http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html" rel="nofollow noreferrer">http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html</a>的学分</p>