When I print the inner class in Python why does it get printed as if it's a module variable (__main__.FInner) rather than getting printed as __main__.F.FInner or something nested?
class F(object):
class FInner:
x = 1
x = F()
print x.FInner # __main__.FInner
or even if I use the newer style inner class style the output remains similar
class F(object):
class FInner(object):
x = 1
x = F()
print x.FInner # <class '__main__.FInner'>
This is because the __repr__() method for classes in Python (or for object maybe?) simply displays module.ClassName by default. Because of this, a class Foo will be displayed as module.Foo regardless of how nested it is within e.g., other classes, because it is still in module.
If you execute your script directly, module will be __main__, but if you import your class in another module, it will show up as my_module.ClassName instead - again, regardless of how nested it is.
The documentation for __repr__() (linked above) says of the string returned by this method:
it is important that the representation is information-rich and unambiguous
In a situation like the following:
>>> class Foo(object):
... class Bar(object):
... class Baz(object):
... pass
...
>>> Foo.Bar.Baz
<class '__main__.Baz'>
<class '__main__.Baz'> is certainly not very "information-rich", nor is it unambiguous, since a top-level class named Baz would have the exact same __repr__() string. However, nested classes in Python are very rare, in my experience as least. Even in the case of a nested class, it is likely that any important information will come from the attributes of the class, or the classes it inherits from, rather than the namespace it happens to occupy. I can certainly understand your curiosity though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With