[Tutor] rationale for nested classes?

Mac Ryan quasipedia at gmail.com
Mon Aug 17 19:12:45 CEST 2009


On Fri, 2009-08-14 at 11:26 -0400, Serdar Tumgoren wrote:
> Hi everyone,
> 
> I was wondering if there's anyone who can offer a use case/rationale
> for nested class?
...
> Are there specific situations when nested classes come in handy
> (perhaps for grouping conceptually related classes that don't share
> attributes?).

Disclaimer: I am not a python-ninja and do not have much python code
under my belt, but since I thought to what I am about to write when I
first read your question, and nobody else gave feedback in this
direction, I though to share my idea, if not for anything else, at least
to be told on why this might be a non pythonic one :) .

I would use a nested class to create a particular data structure which
represent a "sub-unit" of the mother class. For example if I had a class
representing a table (with methods like add, delete, sort, etc...) I
might wish to create a subclass that represent a record and use
instantiation of that sub-class as my main way to handle data. In this
way I could enforce behaviours like "not null" or "default" from within
the datastructure itself (for example in the __init__ method) rather
than enforcing a logic from outside (i.e. the "mother class").

I believe classes/objects are also the most elegant way to implement
singletons, so maybe if you need a singleton for each object generated
with the "mother class", maybe that is also an occasion in which a
subclass comes handy.

Finally, I somewhere read that embedded declarations are much faster
than external ones in being referenced. So, if performance is an issue,
maybe embedding one class within another one might bring you some
benefit rather than having an object instantiated from the first class
having to reference a class which is external to its generating one.
[Hope that is understandable... English is not my first language... :)]

Anyhow let me reiterate my disclaimer: I am not a python guru, so I
would be very happy if any of the tutors would comment on what above,
even if it is for disagree with it! :)

Mac.



More information about the Tutor mailing list