Note that self
not defined at the time you want the class to refer to itself for the job to work. This is because (in addition to being named arbitrarily), self
refers to instances, not classes. While the suspicious line of code is trying to run, there is as yet no class for it. Not that it applied to the class if it was.
In a method, you can always use type(self)
. This will result in a subclass of MyClass
that created the current instance. If you want to hardcode the MyClass
code, this name will be available in the global scope of the methods. This will allow you to do whatever your example allows, if it really works. For example, you can just do MyClass.some_attribute
inside your methods.
You will probably want to change the attributes of the class after creating the class. This can be done using decorators or on a one-time basis. Metaclasses may be better suited. Not knowing what you really want to do is impossible to say.
UPDATE:
Here is the code you want to do. It uses the AutoViewConfigMeta
metaclass and a new decorator to mark the methods to which you want to apply view_config
. I faked the view_config
decorator. He prints out the class name when he calls it to prove that he has access to it. The __new__ __new__
simply scrolls through the class dictionary and searches for methods marked by the auto_view_config
decorator. It clears the label and applies the view_config
decorator with the corresponding class name.
Here is the code.
# This just spoofs the view_config decorator. def view_config(route=''): def dec(f): def wrapper(*args, **kwargs): print "route={0}".format(route) return f(*args, **kwargs) return wrapper return dec
Let me know if you have any questions.
source share