A Revised Rational Proposal

Steven Bethard steven.bethard at gmail.com
Mon Dec 27 00:04:46 EST 2004


Mike Meyer wrote:
> "John Roth" <newsgroups at jhrothjr.com> writes:
> 
> 
>>I'd suggest making them public rather than either protected or
>>private. There's a precident with the complex module, where
>>the real and imaginary parts are exposed as .real and .imag.
> 
> 
> This isn't addressed in the PEP, and is an oversight on my part. I'm
> against making them public, as Rational's should be immutable. Making
> the two features public invites people to change them, meaning that
> machinery has to be put in place to prevent that. That means either
> making all attribute access go through __getattribute__ for new-style
> classes, or making them old-style classes, which is discouraged.

Can't you just use properties?

 >>> class Rational(object):
...     def num():
...         def get(self):
...             return self._num
...         return dict(fget=get)
...     num = property(**num())
...     def denom():
...         def get(self):
...             return self._denom
...         return dict(fget=get)
...     denom = property(**denom())
...     def __init__(self, num, denom):
...         self._num = num
...         self._denom = denom
...
 >>> r = Rational(1, 2)
 >>> r.denom
2
 >>> r.num
1
 >>> r.denom = 2
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: can't set attribute

Steve



More information about the Python-list mailing list