Class definition within function

Peter Otten __peter__ at web.de
Wed Aug 2 08:16:16 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 = type(x)()

By the way you get an instance of a different class C every time you call f,
so that

isinstance(f(), type(f())

is False.

Peter



More information about the Python-list mailing list