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
.
PEP 3155 introduced
__qualname__
, which was implemented in Python 3.3.It is accessible from within the very definition of a class or a function, so for instance:
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.
You can access it by the class' private attributes:
EDIT:
As said by
Ned Batcheler
, this wouldn't work in the class body, but it would in a method.I think, it should be like this:
obj.__class__.__name__
will get you any objects name, so you can do this:Usage:
Within the body of a class, the class name isn't defined yet, so it is not available. Can you not simply type the name of the class? Maybe you need to say more about the problem so we can find a solution for you.
I would create a metaclass to do this work for you. It's invoked at class creation time (conceptually at the very end of the class: block), and can manipulate the class being created. I haven't tested this:
EDIT: Yes, you can; but you have to cheat: The currently running class name is present on the call stack, and the
traceback
module allows you to access the stack.However, I wouldn't do this; My original answer is still my own preference as a solution. Original answer:
probably the very simplest solution is to use a decorator, which is similar to Ned's answer involving metaclasses, but less powerful (decorators are capable of black magic, but metaclasses are capable of ancient, occult black magic)