Home > Software design >  Query attribute name together with its class
Query attribute name together with its class

Time:11-18

The name of an attribute can be asked with __name__. However, I also want to inquire about the class name:

class Test:
    __slots__ = ['a', 'b']

print(Test.a.__name__) # → 'a' but wanted 'Test.a' or only the class 'Test'

CodePudding user response:

Sounds like you want __qualname__.

class Test:
    __slots__ = ['a', 'b']

Test.a.__qualname__
# gives 'Test.a'

See https://www.python.org/dev/peps/pep-3155/

Is there also a magic method of getting the class name only?

You can get the class itself via Test.a.__objclass__. So the name of the class would be available via

Test.a.__objclass__.__name__
# gives 'Test'
  • Related