Overloadable Assignment PEP
Jp Calderone
exarkun at intarweb.us
Thu Apr 3 11:45:16 EST 2003
On Thu, Apr 03, 2003 at 07:05:26AM -0800, Drew Moore wrote:
> "Anders J. Munch" <andersjm at dancontrol.dk> wrote in message news:<3e8c083b$0$10386$edfadb0f at dread11.news.tele.dk>...
> [snip]
>
> > Take a step back and tell us what problem you are trying to solve.
> > Whatever it is, I'm sure we can think of a better solution than having
> > assignment depend on whatever object, if any, happened to be
> > previously bound to the same name.
> >
> > python-is-not-c++-ly y'rs, Anders
>
> my original need?
> I wanted to create an object that controls a voltage and
> use it at the python command line.
> by overloading operators, I can do:
>
> voltage += 5 # (raise the voltage by 5 volts)
> voltage *= 2 # (double the current voltage)
>
> but when I do
>
> voltage = 3 # (set the voltage to 3 volts)
>
> my voltage object is clobbered with an integer object.
> I don't want to require the user to type any more than
> name = value # no name.val = newval, no name.setval(value)
>
class Conductor(object):
def set_voltage(self, value):
# Twiddle whatever needs to be twiddled
def get_voltage(self):
# Lookup whatever the voltage is
return it
voltage = property(get_voltage, set_voltage)
c = Conductor()
c.voltage = 3
This is more along the lines of what you'd really do, anyway, right?
After all, if "voltage" is simply a global, then your program or library
will be forever tied to controlling a single item across which an emf can
be put. Not very scalable, right?
Jp
--
Lowery's Law:
If it jams -- force it. If it breaks, it needed replacing anyway.
--
up 14 days, 12:00, 4 users, load average: 0.00, 0.03, 0.00
More information about the Python-list
mailing list