Let\'s say I create an instance of a class and want to assign some values to its public properties. Usually, this would be done like this:
class MyClass:
After reading rejected Syntax For Dynamic Attribute Access I'm using a mixin class providing dictionary-style access to an object's attributes :
class MyClass:
def __init__(self):
self.name = None
self.text = None
def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
return setattr(self, name, value)
def __delitem__(self, name):
return delattr(self, name)
def __contains__(self, name):
return hasattr(self, name)
While still being able to set attributes directly:
myclass = MyClass()
myclass.name = "foo"
myclass.text = "bar"
it's then possible to set them dynamically :
for attr in ('name', 'text'):
myclass[attr] = confirm(attr, default=myclass[attr])