[Python-Dev] nonstandard behavior of reflected functions (original) (raw)
Darren Dale dsdale24 at gmail.com
Sun Oct 18 17:03:10 CEST 2009
- Previous message: [Python-Dev] nonstandard behavior of reflected functions
- Next message: [Python-Dev] nonstandard behavior of reflected functions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Sun, Oct 18, 2009 at 10:50 AM, Darren Dale <dsdale24 at gmail.com> wrote:
According to http://docs.python.org/reference/datamodel.html , the reflected operands functions like radd "are only called if the left operand does not support the corresponding operation and the operands are of different types. [3] For instance, to evaluate the expression x - y, where y is an instance of a class that has an rsub() method, y.rsub(x) is called if x.sub(y) returns NotImplemented."
Consider the following simple example: ========================== class Quantity(object): def add(self, other): return 'add called' def radd(self, other): return 'radd called' class UnitQuantity(Quantity): def add(self, other): return 'add called' def radd(self, other): return 'radd called' print 'Quantity()+Quantity()', Quantity()+Quantity() print 'UnitQuantity()+UnitQuantity()', UnitQuantity()+UnitQuantity() print 'UnitQuantity()+Quantity()', UnitQuantity()+Quantity() print 'Quantity()+UnitQuantity()', Quantity()+UnitQuantity() ========================== The output should indicate that add was called in all four trials, but the last trial calls radd. Interestingly, if I comment out the definition of radd in UnitQuantity, then the fourth trial calls add like it should. I think this may be an important bug. I'm running Python 2.6.4rc1 (r264rc1:75270, Oct 13 2009, 17:02:06) an ubuntu Karmic. Is it a known issue, or am I misreading the documentation?
I'm sorry, I should have read further down the page in the documentation:
"Note: If the right operand’s type is a subclass of the left operand’s type and that subclass provides the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations."
- Previous message: [Python-Dev] nonstandard behavior of reflected functions
- Next message: [Python-Dev] nonstandard behavior of reflected functions
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]