<p>不需要嵌套类来实现<a href="http://en.wikipedia.org/wiki/Composite_pattern">container pattern</a>。在</p>
<p>将<em>树</em>类移到<em>森林</em>之外。
每次实例化树时,它都可以将自身添加到林中:</p>
<pre><code> class Forest:
def __init__(self):
self.mytrees = []
def add(self, tree):
self.mytrees.append(self)
def drop_leaves(self):
for tree in self.mytrees:
tree.drop_leaves()
class Tree:
def __init__(self, forest):
forest.add(self)
self.var_a = []
self.var_b = []
#Or something as simple
def drop_leaves(self):
print 'Drop'
sherwood = Forest()
t1 = Tree(sherwood)
t2 = Tree(sherwood)
sherwood.drop_leaves()
</code></pre>
<p><strong>问题:</strong></p>
<blockquote>
<p>It is possible to use recursive class in Python3? How does the code
for this look like?</p>
</blockquote>
<p><strong>直接回答:</strong></p>
<p>嵌套类定义在Python中没有任何好处,因为它们的作用域没有嵌套(内部类的内容不能直接引用封闭类)。在</p>
<p>因此,Python中通常的模式是将多个类中的两个类(使用组合而不是继承)直接引用到另一个类中。在</p>
<p><strong>后续评论:</strong></p>
<blockquote>
<p>Well. I don't need to use classes. The functions and dictionaries
would be enough.</p>
</blockquote>
<p>函数和字典总是足够的(Python的早期版本没有类)。噢,我们发现类是组织代码的一种方便的方式,可以清楚地知道哪些函数对哪些数据进行操作。你怎么做这是一个品味问题。在</p>
<p><strong>稍后评论:</strong></p>
<blockquote>
<p>There is one benefit of nested class. Its definition doesn't reside in
global scope.</p>
</blockquote>
<p>这也可能是一个缺点,使得重用代码更加困难,测试更加困难,并且可能会混淆内省工具。在</p>