擅长:python、mysql、java
<p>你可以这样做:</p>
<pre><code>class Shape(object):
_registry = {}
def __new__(cls, name):
if name in cls._registry:
return cls._registry[name]
class Proto(object):
def __init__(self, color, surf_area):
self.color = color
self.surf_area = surf_area
Proto.__name__ = name
cls._registry[name] = Proto
return Proto
</code></pre>
<p>但我一点也不明白-你的“动态”类根本没有行为,所有的类都有完全相同的属性集,所以你可以只使用一个类,而得到完全相同的行为:</p>
<pre><code>class Shape(object):
def __init__(self, typename, color, surf_area):
self.typename = typename
self.color = color
self.surf_area = surf_area
def __repr__(self):
return "<Shape({}) at {}>".format(self.typename, id(self))
blue_circle = Shape("Circle", "blue", 78.4222)
</code></pre>
<p>这<a href="http://xyproblem.info/" rel="nofollow noreferrer">looks like a XY problem</a>对我来说,你也许应该告诉更多关于你试图用这个来解决的真正问题。你知道吗</p>