In Python, how do I get a reference to the current class object within a class statement? Example:
def setup_class_members(cls, prefix):
setattr(cls, prefix+"_var1", "hello")
setattr(cls, prefix+"_var2", "goodbye")
class myclass(object):
setup_class_members(cls, "coffee") # How to get "cls"?
def mytest(self):
print(self.coffee_var1)
print(self.coffee_var2)
x = myclass()
x.mytest()
>>> hello
>>> goodbye
Alternatives that I've written off are:
Use
locals(): This gives a dict in a class statement that can be written to. This seems to work for classes, however the documentation tells you not to do this. (I might be tempted to go with this alternative if someone can assure me that this will continue to work for some time.)Add members to the class object after the
classstatement: My actual application is to derive a PyQt4QWidgetclass with dynamically createdpyqtPropertyclass attributes.QWidgetis unusual in that it has a custom metaclass. Very roughly, the metaclass compiles a list ofpyqtPropertiesand stores it as additional member. For this reason, properties that are added to the class after creation have no effect. An example to clear this up:
from PyQt4 import QtCore, QtGui
# works
class MyWidget1(QtGui.QWidget):
myproperty = QtCore.pyqtProperty(int)
# doesn't work because QWidget's metaclass doesn't get to "compile" myproperty
class MyWidget2(QtGui.QWidget):
pass
MyWidget2.myproperty = QtCore.pyqtProperty(int)
Please note that the above will work for most programming cases; my case just happens to be one of those unusual corner cases.
type(class_name, bases_tuple, locals_dict)which then returnscls. Thus,clsisn't available at the point you want, only afterwards. Also, using a metaclass will cause it to be called in place oftype, and with the same signature. - Eli Collinslocals()trick working in classes. Interesting bit of trivia. :-) - kindall