class declaration shortcut

Arnaud Delobelle arnodel at googlemail.com
Fri Mar 2 18:14:13 EST 2007


On Mar 2, 8:28 pm, Bjoern Schliessmann <usenet-
mail-0306.20.chr0n... at spamgourmet.com> wrote:
> This is somehow contrary to my understanding of the Python names
> concept.
>
> What if I use a loop to define several classes based on data --
> they'll all have the same __name__ unless I change it manually.

Well that's not a typical way of defining classes.  It is then your
job to name those classes.

> Having this __name__ attribute set seems to me like "magic behind
> the lines" which Python strives to evade, doesn't it? Personally,
> I'd prefer inserting a mechanism for this manually if and when I
> really need the functionality, but see below.

So you want a Class object without a __name__, and then you would
subclass it to NamedClass with a __name__.
OTOH every class that you define in python using the 'class' keyword
has an obvious name (the identifier that follows the 'class' keyword),
so it seems natural to me to endow each defined class with a __name__.

> > What I described above is quite useful I think.  The alternative
> > (anonymous classes) is that given an object myobj you have no
> > means to find out what its class is (by that I mean to be able to
> > locate the class definition in your source code), apart from
> > stabbing in the dark (i.e. trying type(myobj)==someclass until
> > successful).
>
> In the typical case where you have one name per class definition,
> yes.

As you say this is the typical case, and a __name__ attribute is very
useful in this case.  For the minority of cases when you have a class
factory for example, then I guess it is your responsibility to name
the class appropriately.

IMHO if you create classes in a way that makes it  impossible to name
them naturally, then it is likely that you are misusing the class
object.

> Perhaps I'm lacking a typical application of __name__; that must be
> why I'm so stubborn here ;)

Here are 3 (please correct me if I'm wrong)

>>> class Foo: pass
>>> Foo    # typical application 1
<class __main__.Foo at 0x136ef30>
>>> foo=Foo()
>>> foo    # typical application 2
<__main__.Foo instance at 0x1372788>
>>> pickle.dumps(foo)    # typical application 3
 '(i__main__\nFoo\np0\n(dp1\nb.'

--
Arnaud




More information about the Python-list mailing list