I looked at the answer to this question: Is it possible to define a class constant inside Enum?
I was most interested in the constant class in Ethan Furman's answer.
class Constant: def __init__(self, value): self.value = value def __get__(self, *args): return self.value def __repr__(self): return '%s(%r)' % (self.__class__.__name__, self.value)
The question was about Python 3.4, but I'm using 2.7. In the answer, Ethan sets the gravitational constant as an instance variable of the Planet class like this:
G = Constant(6.67300E-11)
My testing of this class in 2.7 shows that only G input gives me the following:
Out[49]: Constant(3)
(I set it to 3 for ease of use during testing. It looks like __repr__ output to me, please correct me if I'm wrong.)
The value is available through G.value. However in ethan's answer he uses
return self.G * self.mass / (self.radius * self.radius)
This obviously only works if the value returns to __repr__ . Now, if I change class Constant: to class Constant(int): then type G, I still get the __repr__ output, but if I type G * 4 , I get 12 not the error I was getting. (TypeError: unsupported operand type for *: 'instance' and 'int')
So it is clear that something like an int object can output a number when called. Is there a magic method that I skip that will allow me to do this for the Constant class? Since constants can be strings, integers or floats, I would prefer to have 1 class that processes them all against 3 separate classes that extend these objects.
The value is also set via G.value. Can I block this so that the Constant class behaves like a real constant? (I suspect the answer is no.)
python enums class
Gabe spradlin
source share