- Mastering Objectoriented Python
- Steven F. Lott
- 186字
- 2021-11-12 16:25:13
Note
Note that we can't set attribute values inside this class definition easily.
Let's consider the following line of code:
self.distance = self.rate*self.time
If we were to write the preceding code snippet, we'd have infinite recursions between __setattr__()
and _solve()
. When we used self['distance']
in the example, we avoided the recursive call of __setattr__()
.
It's also important to note that once all three values are set, this object can't be changed to provide new solutions easily.
We can't simply set a new value for rate
and compute a new value for time
while leaving distance
unchanged. To tweak this model, we need to both clear one variable and set a new value for another variable:
>>> rtd.time= None >>> rtd.rate= 6.1 >>> print( "Rate={rate}, Time={time}, Distance={distance}".format( **rtd ) ) Rate=6.1, Time=8.25, Distance=50.324999999999996
Here, we cleared time
and changed rate
to get a new solution for time
using the established value for distance
.
We could design a model that tracked the order that the variables were set in; this model could save us from having to clear one variable before setting another to recompute a related result.