-
-
Save objarni/3720182 to your computer and use it in GitHub Desktop.
import random | |
class Sensor(object): | |
OFFSET = 16 | |
def pop_next_pressure_psi_value(self): | |
pressure_telemetry_value = self.sample_pressure() | |
return Sensor.OFFSET + pressure_telemetry_value | |
def __iter__(self): | |
return iter(self.pop_next_pressure_psi_value, Ellipsis) | |
@staticmethod | |
def sample_pressure(): | |
# placeholder implementation that simulate a real sensor in a real tire | |
pressure_telemetry_value = 6 * random.random() * random.random() | |
return pressure_telemetry_value | |
class TirePressureAlarm(): | |
def __init__(self): | |
self.fuse = Fuse( | |
condition=lambda value : not 17 <= value <= 21, | |
iterator=iter(Sensor()) | |
) | |
def check(self): | |
self.fuse.check() | |
def is_alarm_on(self): | |
return self.fuse.on | |
Alarm = TirePressureAlarm | |
class Fuse(object): | |
def __init__(self, condition, iterator): | |
self.__conditon = condition | |
self.__iterator = iterator | |
self.__on = False | |
def check(self): | |
value = self.__iterator.next() | |
self.__on = self.on or self.__conditon(value) | |
@property | |
def on(self): | |
return self.__on |
Why "self.__on = self.on or self.__conditon(value)"? Why not "self.__on = self.__on or self.__conditon(value)"?
Are you expecting a sub class to return anything else than self.__on from self.on?
Oh I missed all these comments until now! (why doesn't github notify me when ppl comment on my gist?). I just read about the single/double underscore in docs, maybe single underscore is a little more "agile" since double underscores kind of assumes you are subclassing (it does some naming magic wizardry which I didn't quite follow..). Single _underscore convention just means " these members are subject to API changes without notice". [everything is a convention no real private vars in Python that I know of..]
Thanks for finding the docs, Andre. So even __ is not really private, you can still get at it from the outside. So the convention is to use _ most of the time, and __ when that doesn't work. So I think in this code, single underscores would work fine.
@emilybache i do agree that _
is enough though I think that the "you can still get to it" is the wrong reason. Unless you think privat in Java is not private, since you can get to that with reflections...
Any mays, i have ssen that you changed it in your code, but you made the alarm_on method only a public variable, letting the interface the user change the value and not only read it. And also i though that the Java-nes of the code was quite fun to pythonify.
Yes, __ is private. _ is a "weak internal use indicator". The only way Python cares about it is that "from X import *" won't import names starting with _, but you shall never use "from X import *" in production code anyway, so that doesn't really matter.
See http://www.python.org/dev/peps/pep-0008/