<p>我同意<a href="https://stackoverflow.com/questions/3076537/python-virtual-classes-doing-it-right/3076563#3076563">TooAngel</a>,但我会使用<a href="http://docs.python.org/reference/datamodel.html#object.__new__" rel="nofollow noreferrer"><em>__new__ method</em></a>。</p>
<pre><code>class Shape(object):
def __new__(cls, *args, **kwargs):
if cls is Shape: # <-- required because Line's
description, args = args[0], args[1:] # __new__ method is the
if description == "It's flat": # same as Shape's
new_cls = Line
else:
raise ValueError("Invalid description: {}.".format(description))
else:
new_cls = cls
return super(Shape, cls).__new__(new_cls, *args, **kwargs)
def number_of_edges(self):
return "A shape can have many edges…"
class Line(Shape):
def number_of_edges(self):
return 1
class SomeShape(Shape):
pass
</code></pre>
<hr/>
<pre><code>>>> l1 = Shape("It's flat")
>>> l1.number_of_edges()
1
>>> l2 = Line()
>>> l2.number_of_edges()
1
>>> u = SomeShape()
>>> u.number_of_edges()
'A shape can have many edges…'
>>> s = Shape("Hexagon")
ValueError: Invalid description: Hexagon.
</code></pre>