class object access in class definition?

Lars Damerow lars at pixar.com
Wed Mar 7 21:40:45 EST 2001


I figured that the my problem stems from when Python binds the class name to
the scope--when it encounters the "class" keyword, or when the class definition
completes. It seems like it happens when the class definition completes.

What I'm trying to do is automatically register the derived classes of a base
class at compile time, like this:

derivedClasses = []

class BaseClass:
    pass

class DerivedClass(BaseClass):
    derivedClasses.append(DerivedClass)

This doesn't work because DerivedClass doesn't seem to be bound at the time of
the append() call. I can put the append() call in the DerivedClass's
constructor, but that requires an instance to be created before the class can
be registered.

If this isn't possible, it's no big deal; its goal is to avoid duplicating
information in the code, nothing more.

thanks!
-lars

On 7 Mar 2001, Remco Gerlich wrote:

| Lars Damerow <lars at pixar.com> wrote in comp.lang.python:
| > Is it possible to reference a class from within its own definition? Something
| > along the lines of:
| > 
| > class Foo:
| >     print Foo
| > 
| > This works for functions--that is,
| > 
| > >>> def foo():
| > ...     print foo
| > ...
| > >>> foo()
| > <function foo at 0x8111024>
| > 
| > works as expected, but the class definition above raises a NameError:
| > 
| > >>> class Foo:
| > ...     print Foo
| > ...
| > Traceback (most recent call last):
| >   File "<stdin>", line 1, in ?
| >   File "<stdin>", line 2, in Foo
| > NameError: There is no variable named 'Foo'
| 
| The difference is that the function is executed *after* you defined it, so
| that by then the name exists. In the case of the class, it is executed
| during its definition, and at that time the name doesn't exist yet.
| 
| I have no idea what you're trying to do, but maybe a workaround is to create
| an empty class of another name first, and inherit from that. You can then
| use references to that class, and be able to influence the current class.
| 
| But well, no idea what you're trying to do :)
| 
| -- 
| Remco Gerlich
| 

___________________________________________________________
lars damerow
button pusher
lars at pixar.com

Eat Snacky Smores!




More information about the Python-list mailing list