Scoped change of a global variable
Luigi Ballabio
ballabio at mac.com
Wed Jan 2 07:30:20 EST 2002
Corrado,
At 11:53 AM 1/2/02 +0100, Corrado Gioannini wrote:
>On Wed, Jan 02, 2002 at 11:29:45AM +0000, Luigi Ballabio wrote:
>[...snip...]
>
>You could define a class like:
>
>precision = 2
>class Add:
> def __init__(self):
> self.precision = precision
> def add(self, x, y):
> ...
> def setPrecision(self, n):
> self.precision = n
> def restorePrecision(self):
> self.precision = precision
>
>and then simply:
>
>a = Add()
>a.add(1.0, 0.3456)
>a.setPrecision(3)
>a.add(1.0, 0.3456)
>a.restorePrecision()
Well, the logic is only half-encapsulated here---you still have to call
restorePrecision() explicitly.
>This if you really don't want to use parameters...
>
>precision = 2
>def add(x, y, z=precision):
Well, add(x,y) was a simple way to write an example. My real purpose would
be the __add__ method for a class of a numeric kind, which can only take
the two operands as parameters. The corresponding Ruby example would be:
withPrecision(1) {
a = b+c
}
Grazie comunque,
Luigi
More information about the Python-list
mailing list