Is it possible to conditionally override a class property with a property method?
If I have this class which I can instantiate by passing in a dict:
def Foo(Object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
# pseudo code (this doesn't work)
if not self.bar:
@property
def bar(self):
return u"I have overridden foo's bar"
And I make this instance and set bar to '' or None:
my_foo = Foo(**{'bar':u''})
and then I call the bar property:
my_foo.bar
and get
u"I have overridden foo's bar"
I would like to have the property method bar returned, instead of the bar value that was passed in when the object was created.
Can I do that somehow? Any help would be awesome.
To override a property you have to act on the class and not on the instance, because their machinery, on the instance, gets called before
__dict__lookup and you end up withAttributeErrors. Instead you can set a different property on the class.But to do so you either have to modify your class every time you create an instance(which I bet you do not want), or you have to generate new classes dynamically.
For example:
And the results are:
I don’t like much this kind of hacks. Probably the easier way of doing thing is calling a private method that computes the property value, for example:
Which yields the same results as before:
I believe this trick could be seen as an application of the Template Method design pattern, even though it is applied to properties.