anything like C++ references?
Bengt Richter
bokr at oz.net
Tue Jul 15 15:04:15 EDT 2003
On Mon, 14 Jul 2003 16:44:09 -0700, Tom Plunket <tomas at fancy.org> wrote:
>Noah wrote:
>
>> As others have explained, you just return the value.
>> It's just a different point of view. Instead of
>> change (v)
>> you have:
>> v = change (v)
>
>Ahh, now I remember what I wanted to do, and you're right- it's
>more verbose and didn't really seem to add anything. I wanted to
>in-place clamp integers in a range, or maybe they were even
>member variables;
>
>def Color:
> def SomeOperation():
> # modify self.r, g, b
> self.r = clamp(self.r, 0, 255)
> self.g = clamp(self.g, 0, 255)
> self.b = clamp(self.b, 0, 255)
>
>...that was just more typing than I wanted at that point,
>although I'm sure that the keystrokes I burned were more than
>made up for by Python's allowing me to do:
>
> def clamp(val, lowVal, highVal):
> if (lowVal <= val <= highVal):
> return val
>
Doesn't clamping ususally return the limit values when exceeded?
E.g.,
def clamp(val, lowVal, highVal): return max(lowVal, min(val, highVal))
Also, if you are dealing with member variables, you can clamp them whenever
they are set (including via __init__ code ;-), e.g., (here I built in the
clamping code and constants, though it might make sense to parameterize the
limits in generating a class or subclass for instances that are all to be
clamped the same):
>>> class RGB(object):
... def __init__(self, r=0, g=0, b=0): self.r=r; self.g=g; self.b=b
... def __setattr__(self, name, val):
... if name in ('r', 'g', 'b'): object.__setattr__(self, name, max(0, min(val, 255)))
... else: object.__setattr__(self, name, val)
... def __repr__(self): # just so we can see easily
... return '<RGB instance (%s, %s, %s) at 0x%x>' % (self.r, self.g, self.b, id(self))
...
>>> o = RGB(-3,22,512)
>>> o
<RGB instance (0, 22, 255) at 0x7d8e10>
>>> o.g = 256
>>> o
<RGB instance (0, 255, 255) at 0x7d8e10>
>>> o.b = -1
>>> o
<RGB instance (0, 255, 0) at 0x7d8e10>
>>> o.r, o.g, o.b
(0, 255, 0)
>>> o.g
255
>>> o.other = 'not clamped'
>>> o
<RGB instance (0, 255, 0) at 0x7d8e10>
>>> o.other
'not clamped'
(Of course, you wouldn't want to use this kind of RGB object to represent pixels
where you had to process a lot of them fast ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list