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.
AFAIK there is two way to do what you want:
Using metaclass, this will create your two variables in class creation time (which i think is what you want):
Create your two class variable in instantiation time:
class myclass(object):
prefix = “coffee”
N.B: I’m not sure what you want to achieve because if you want to create dynamic variables depending on the
prefixvariable why are you accessing like you do in yourmytestmethod ?! i hope it was just an example.