Class definition within function

Duncan Booth duncan.booth at invalid.invalid
Wed Aug 2 08:24:26 EDT 2006


Tomi Lindberg wrote:

> With the following function definition, is it possible to 
> create an instance of class C outside the function f (and if 
> it is, how)? And yes, I think this is one of those times 
> when the real question is why :)
> 
> >>> def f():
>      class C(object):
>           def __init__(self):
>                self.a = 'a'
>      return C()
> 
> >>> x = f()
> >>> x.a
> 'a'
> >>> y=f.C()
> 
> Traceback (most recent call last):
>    File "<pyshell#22>", line 1, in -toplevel-
>      y=f.C()
> AttributeError: 'function' object has no attribute 'C'
> >>>
> 

Well, you could use 'type(x)()', or object.__subclasses__() will include C 
for as long as the class actually exists. Choosing the correct C from 
object's subclasses could prove somewhat tricky though: remember you'll get 
a new C class every time you call 'f'.



More information about the Python-list mailing list