Situation
Like this question , I want to replace a property. Unlike this question, I do not want to redefine it in a subclass. I want to replace it in init and in the property itself for efficiency, so that it does not need to call a function that evaluates the value each time the property is called.
I have a class that has a property on it. The constructor can take a property value. If a value is passed to it, I want to replace the property with a value (and not just set the property). This is because the property itself calculates a value, which is an expensive operation. Similarly, I want to replace a property with the value computed by the property as soon as it has been calculated, so that future calls to the property do not need to be re-read:
class MyClass(object): def __init__(self, someVar=None): if someVar is not None: self.someVar = someVar @property def someVar(self): self.someVar = calc_some_var() return self.someVar
Problem
The above code does not work because self.someVar = does not replace the someVar function. It tries to call the setter property, which is undefined.
Potential solution
I know that I can achieve the same a little bit as follows:
class MyClass(object): def __init__(self, someVar=None): self._someVar = someVar @property def someVar(self): if self._someVar is None: self._someVar = calc_some_var() return self._someVar
This will be marginally less efficient, as each time the property is called, it will check None. The app has critical performance, so it may or may not be good enough.
Question
Is there a way to replace a property with an instance of the class? How much more efficient would it be if I could do this (i.e. Avoid checking None and calling a function)?
source share