2

Given a nested class B:

class A:
    class B:
        def __init__(self):
            pass

ab = A.B()

How can I get the full name of the class for ab? I'd expect a result like A.B.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • 1
    Why are you nesting classes? What do you need that name for? What's the actual problem you're trying to solve? – jonrsharpe Sep 29 '16 at 09:03
  • One of my strongest reason is that is show like good practice for modules. For example i have one class which is envelope for all module. I use it because python hasnt perfect solution for modules. second reason it is better decomposition of problem. – Honza Šeda Sep 29 '16 at 09:12
  • 2
    That's not a great reason; Python *does* have a solution for modules, and it's, err, modules. The file, or directory containing `__init__.py`, is the module. You don't have to wrap everything in classes, this isn't Java. Maybe you should have asked that question instead. – jonrsharpe Sep 29 '16 at 09:13
  • http://stackoverflow.com/questions/2020014/get-fully-qualified-class-name-of-an-object-in-python – Padraic Cunningham Sep 29 '16 at 09:20
  • Yes, i know and i use `__init__.py`. I would like discuss about this with someone who has deep knowledge. I decided for this wrapping solution few months ago. Now i am not able perfectly describe my trouble which i had. Simply i dont remmber. But I would have other question. What you see like good practice for using class nesting. Thank you. – Honza Šeda Sep 29 '16 at 09:25
  • 3
    The good practice is: don't nest classes. There's almost always another, better way to do whatever you're doing. – jonrsharpe Sep 29 '16 at 09:29

1 Answers1

9

You could get the fully qualified name, __qualname__, of its __class__:

>>> ab.__class__.__qualname__
'A.B'

Preferably by using type (which calls __class__ on the instance):

>>> type(ab).__qualname__
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253