I have a number of classes with code like this. Each __init__
starts a thread and a logger with the name of the class. How do I get the name of the current class in its own definition, as a string, inside __init__
? Note that self
may not be an instance of the current class, so the following is not quite foolproof.
from threading import Thread
import logging
def myClassName(myclass):
myclass._class_name = myclass.__name__
return myclass
@myClassName
class SomeClass(object):
def __init__(self):
class_name = type(self)._class_name
print "My class name in __init__ is", class_name
self.thread = Thread(name=class_name)
self.logger = logging.getLogger(class_name)
Update:
To clarify:
- I want the name of the class being defined, not the class of the object passed in.
- I don't want to hard code the name of the class.
- I want to make it easy to copy/paste an example from one script to
another, and the fewer mentions of the unique class name, the better. (Inheritance isn't really efficient, as there are enough custom differences to make it awkward. But accidentally leaving in the name of the wrong class is a hard bug to find.)