The goal is to create a mock class which behaves like a db resultset.
So for example, if a database query returns, using a dict expression, {\'ab\':100, \'cd\'
For those coming from search engines, here are the two things I was looking for when talking about dynamic properties:
class Foo:
def __init__(self):
# we can dynamically have access to the properties dict using __dict__
self.__dict__['foo'] = 'bar'
assert Foo().foo == 'bar'
# or we can use __getattr__ and __setattr__ to execute code on set/get
class Bar:
def __init__(self):
self._data = {}
def __getattr__(self, key):
return self._data[key]
def __setattr__(self, key, value):
self._data[key] = value
bar = Bar()
bar.foo = 'bar'
assert bar.foo == 'bar'
__dict__
is good if you want to put dynamically created properties. __getattr__
is good to only do something when the value is needed, like query a database. The set/get combo is good to simplify the access to data stored in the class (like in the example above).
If you only want one dynamic property, have a look at the property() built-in function.