What is the reason for defining classes within classes in Python?

alex23 wuwei23 at gmail.com
Tue Apr 23 20:50:36 EDT 2013


On Apr 24, 9:13 am, vasudevram <vasudev... at gmail.com> wrote:
> On Wednesday, April 24, 2013 3:52:57 AM UTC+5:30, Ian wrote:
> > On Tue, Apr 23, 2013 at 3:50 PM, vasudevram  wrote:
> > > I saw an example of defining a class within another class
> > > In what way is this useful?
>
> > In that particular case they're just using it as a namespace.
>
> Not clear. An example or more explanation might help, if you can. Thanks.

Namespaces are used to allow for the same label to be applied to
different concepts without the labels conflicting with each other. If
I was writing a program that dealt with the mathematics of morality, I
might want to use the sine function and refer to it in the standard
way as 'sin', and I might also want to store a value representing your
lack of goodness as 'sin'. As you can't use the same label in the same
scope to refer to two different objects, one way of dealing with this
that lets you still use what you feel are the most appropriate names
is to put them into a namespace. So you could express this as:

    class Math(object):
        sin = function()

    class Morality(object):
        sin = True

Then in your code you can clearly distinguish between the two by using
Math.sin and Morality.sin. Modules & packages are also namespaces, so
in this example we'd replace the Math class with `import math`, which
has a sin function defined within it.

A nested class definition will be defined as an attribute of the class
its defined within:

>>> class Outer(object):
...     foo = 'FOO'
...     class Inner(object):
...         bar = 'BAR'
...
>>> Outer.Inner
<class '__main__.Inner'>
>>> Outer.Inner.bar
'BAR'

With peewee, the Model class looks for a Meta attribute and uses
attributes on it to perform some tasks, like where to retrieve/store
the model data. This allows for a way of distinguishing between
attributes used to define fields, and attributes needed for those
tasks. It also means your Models can use field names that the class
would otherwise reserve for its own internal purposes:

    class DatabaseDetails(Model):
        # these attributes are fields
        database = CharField()
        owner = CharField()

        # ...but the Meta attribute isn't
        class Meta:
            # these attributes are used by the Model class
            database = db

Here, database as a field is a text string that could contain a
database name, while DatabaseDetails.Meta.database contains a
reference to an actual database where the DatabaseDetails record would
be stored.



More information about the Python-list mailing list