Look at this code:
class MyClass():
# Why does this give me "NameError: name 'self' is not defined":
mySelf = self
# But this does not?
def myFunction(self):
mySelf2 = self
Basically I want a way for a class to refer to itself without needing to name itself specifically, hence I want self to work for the class, not just methods/functions. How can I achieve this?
EDIT: The point of this is that I’m trying to refer to the class name from inside the class itself with something like self.class._name_ so that the class name isn’t hardcoded anywhere in the class’s code, and thus it’s easier to re-use the code.
EDIT 2: From what I’ve learned from the answers below, what I’m trying to do is impossible. I’ll have to find a different way. Mission abandoned.
EDIT 3: Here is specifically what I’m trying to do:
class simpleObject(object):
def __init__(self, request):
self.request = request
@view_defaults(renderer='string')
class Test(simpleObject):
# this line throws an error because of self
myClassName = self.__class__.__name__
@view_config(route_name=myClassName)
def activateTheView(self):
db = self.request.db
foo = 'bar'
return foo
Note that
selfis not defined at the time when you want the class to refer to itself for the assignment to work. This is because (in addition to being named arbitrarily),selfrefers to instances and not classes. At the time that the suspect line of code attempts to run, there is as of yet no class for it to refer to. Not that it would refer to the class if there was.In a method, you can always use
type(self). That will get the subclass ofMyClassthat created the current instance. If you want to hard-code toMyClass, that name will be available in the global scope of the methods. This will allow you to do everything that your example would allow if it actually worked. E.g, you can just doMyClass.some_attributeinside your methods.You probably want to modify the class attributes after class creation. This can be done with decorators or on an ad-hoc basis. Metaclasses may be a better fit. Without knowing what you actually want to do though, it’s impossible to say.
UPDATE:
Here’s some code to do what you want. It uses a metaclass
AutoViewConfigMetaand a new decorator to mark the methods that you wantview_configapplied to. I spoofed theview_configdecorator. It prints out the class name when it’s called though to prove that it has access to it. The metaclass__new__just loops through the class dictionary and looks for methods that were marked by theauto_view_configdecorator. It cleans off the mark and applies theview_configdecorator with the appropriate class name.Here’s the code.
Let me know if you have any questions.