Is it possible to set an attribute in a class dynamically? That is I don’t want to have the attribute (e.g. could be a property) defined in the body of the class directly, I want it to be defined later via setattr on user input.
# this is the callback from a UI EnumProperty
def update_type(self, context):
self.update_props()
# the valueA attribute exists at this point
print(“valueA = “, self.valueA)
def update_props(self):
if hasattr(self, "valueA"):
print("Deleting valueA prop")
delattr(self, "valueA")
else:
# note: it appears that the valueA does not exist
# even after a second call to this method.
print("valueA prop not found. Create one.")
setattr(self, “valueA”, 10)
for some reason (unclear to me at this point) even though the valueA gets set in the update_props() method and it’s visible its caller change_type, the next time the caller invokes the update_props() the valueA attribute does not exist anymore.
Note: this code was added to a blender add-on (sverchok) and I can’t guarantee that the above behavior is a blender or sverchok related at this point. If the above code is added to a simple class in python terminal for instance, it works fine and the attribute gets set permanently in the instance of the class.
type(self)
in this context? $\endgroup$setattr
here in the first place?setattr(self, 'valueA', 10)
is exactly the same asself.valueA = 10
. $\endgroup$setattr
allows you to dynamically set dotted attributes from variables. if you had a function that you wanted to be able to pass any attribute to a class to set, you couldn't write that function asdef foo(class_name, attr, val): class_name.attr = val
, but writing it asdef foo(class_name, attr, val): setattr(class_name, 'attr', val)
circumvents that. Especially comes in handy when other dynamic functions are passing variables to this function at runtime. $\endgroup$