Get name of current class?

Viewed 126223

How do I get the name of the class I am currently in?

Example:

def get_input(class_name):
    [do things]
    return class_name_result

class foo():
    input = get_input([class name goes here])

Due to the nature of the program I am interfacing with (vistrails), I cannot use __init__() to initialize input.

9 Answers

PEP 3155 introduced __qualname__, which was implemented in Python 3.3.

For top-level functions and classes, the __qualname__ attribute is equal to the __name__ attribute. For nested classes, methods, and nested functions, the __qualname__ attribute contains a dotted path leading to the object from the module top-level.

It is accessible from within the very definition of a class or a function, so for instance:

class Foo:
    print(__qualname__)

will effectively print Foo. You'll get the fully qualified name (excluding the module's name), so you might want to split it on the . character.

However, there is no way to get an actual handle on the class being defined.

>>> class Foo:
...     print('Foo' in globals())
... 
False

@Yuval Adam answer using @property

class Foo():
    @property
    def name(self):
        return self.__class__.__name__

f = Foo()
f.name  # will give 'Foo'

I think, it should be like this:

    class foo():
        input = get_input(__qualname__)

I'm using python3.8 and below is example to get your current class name.

class MyObject():
    @classmethod
    def print_class_name(self):
        print(self.__name__)

MyObject.print_class_name()

Or without @classmethod you can use

class ClassA():
    def sayhello(self):
        print(self.getName())
    
    def getName(self):
        return self.__class__.__name__

  ClassA().sayhello()

Hope that helps others !!!

Related