What is the reason for defining classes within classes in Python?

Peter Otten __peter__ at web.de
Wed Apr 24 08:00:55 EDT 2013


vasudevram wrote:

> On Wednesday, April 24, 2013 6:20:36 AM UTC+5:30, alex23 wrote:
>> 
>> A nested class definition will be defined as an attribute of the class
>> 
>> its defined within:
>> 
>> 
>> 
>> >>> class Outer(object):
>> 
>> ...     foo = 'FOO'
>> 
>> ...     class Inner(object):
>> 
>> ...         bar = 'BAR'
>> 
>> ...
>> 
>> >>> Outer.Inner

> Just one other doubt:
> 
>> >>> Outer.Inner
>> 
>> <class '__main__.Inner'>
>> 
> 
> In the above output, I would have thought Python would print
> __main__.Outer.Inner or Outer.Inner instead of __main__.Inner, since Inner
> is an attribute of Outer?

The Python developers seem to agree with you and have made the compiler 
smart enough to accomodate your expectations in Python 3.3:

$ cat tmp.py
class Outer:
    class Inner:
        pass

print(Outer.Inner)
$ python3.2 tmp.py
<class '__main__.Inner'>
$ python3.3 tmp.py
<class '__main__.Outer.Inner'>





More information about the Python-list mailing list