class object access in class definition?

Remco Gerlich scarblac at pino.selwerd.nl
Wed Mar 7 05:22:52 EST 2001


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



More information about the Python-list mailing list