Getting a class attribute
Johann Hibschman
johann at physics.berkeley.edu
Fri Mar 24 13:57:00 EST 2000
Alex writes:
>> It is possible to get the class atribute "a" in the default function
>> parameter?
> My understanding is that the default values are computed at compile
> time, so not really. Perhaps you could redefine the function each time
> the member 'a' changes? Here is an example. It does not really make
> new_degree_sin4 into a class method, as I don't know how. I am pretty
> sure it's possible and desirable to do so, though. Hopefully someone
> else will tell you.
AFAIK, you would have to make the function a *class* variable.
i.e. change
> import math
> class Eg:
> def __init__ (self):
> self.set_factor (1)
> def set_factor (self, a):
> self.a = a
> def new_degree_sin4 (deg, factor=(a*(math.pi/180)),
> sin=math.sin):
> return sin (deg * factor)
> self.new_degree_sin4 = new_degree_sin4
to
def set_factor(self, a):
self.a = a
# i.e. now I include self in the method signature
def new_degree_sin4(self, deg, factor=(a*(math.pi/180)), sin=math.sin):
return sin (deg * factor)
# and set the value in the class, not the instance
Eg.new_degree_sin4 = new_degree_sin4
> if __name__ == '__main__':
> eg = Eg ()
> print eg.new_degree_sin4 (5)
> eg.set_factor (6)
> print eg.new_degree_sin4 (5)
That lets you get access to "self", but at the cost of rewriting the
class method itself. Hm. Now that I think about it, this seems like
a Really Bad Idea, since if you had multiple instances, you'd be
overwriting the same class method each time.
Maybe someone more wizardly than I can answer this. Just don't say
"metaclass" three times, or you'll summon a Horror.
--
Johann Hibschman johann at physics.berkeley.edu
More information about the Python-list
mailing list