Carl Von
Carl Von

Reputation: 178

How to get the full class name of a sub-class with Python

I need to get the full name of a subclass.

Example:

class Foo:
    class Bar:
        pass


x = Foo.Bar()
print(x.__class__.__name__)

Output: Bar
Expected: Foo.Bar

Upvotes: 2

Views: 87

Answers (2)

Carlo Zanocco
Carlo Zanocco

Reputation: 2019

You can use the __qualname__, this is the fully qualified name of the __class__

class Foo:
    class Bar:
        pass


x = Foo.Bar()
print(x.__class__.__qualname__)
#OUTPUT: Foo.Bar

The best way is to call it on the type, it alredy call __class__ on instance:

class Foo:
    class Bar:
        pass


x = Foo.Bar()
print(type(x).__qualname__)
#OUTPUT: Foo.Bar

Upvotes: 2

jupiterbjy
jupiterbjy

Reputation: 3503

Use type.

class Foo:
    class Bar:
        pass


x = Foo.Bar()
print(type(x))
<class '__main__.Foo.Bar'>

Strip __main__ or not, up to you.

Upvotes: 0

Related Questions