Classes in a class: how to access variables from one in another

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Tue Oct 19 00:52:29 EDT 2010


On Mon, 18 Oct 2010 20:37:34 -0700, alex23 wrote:

> Steven D'Aprano <st... at REMOVE-THIS-cybersource.com.au> wrote:
>> I'll accept that nested classes are unusual, but unPythonic? Never!
> 
> Not even if "flat is better than nested" ;)

But "Namespaces are one honking great idea -- let's do more of 
those!" (classes are a good thing) and "Readability counts." (namespace 
pollution is a bad thing).


> And are you the same Steven D'Aprano who once wrote:
> 
> "Never nest classes, unless you need to, or to win a bet."

Yep, that was me. And I stand by it. Most of the time non-nested 
solutions is the best solution. But when it's not, there's nothing wrong 
with nesting classes. After all, a nested class is no more scary than a 
nested function.


> Given that there's little if anything gained from nesting classes (other
> than possible scoping confusion) is there ever a need?

Avoiding namespace pollution and information hiding are two good reasons 
for nesting classes. Take this recipe for example:


http://code.activestate.com/recipes/252524


There's no need to expose the Node class, and no reason not to nest it. 
Nor is there particularly any reason to nest it, other than those given 
above. But it is a matter of choice -- the author choose not to nest the 
class, but he could easily have chosen to. If the author had valued 
information hiding over one extra indent level, then I would call that a 
need.



-- 
Steven



More information about the Python-list mailing list