[ python-Bugs-871378 ] __getattr__ and __add__ collides
SourceForge.net
noreply at sourceforge.net
Wed Jan 7 14:46:21 EST 2004
Bugs item #871378, was opened at 2004-01-05 21:12
Message generated for change (Comment added) made by rhettinger
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=871378&group_id=5470
Category: Python Interpreter Core
Group: Python 2.3
>Status: Closed
>Resolution: Invalid
Priority: 5
Submitted By: Huang Guang Shen (shhgs)
Assigned to: Nobody/Anonymous (nobody)
Summary: __getattr__ and __add__ collides
Initial Comment:
My English is not good enough, so I'd rather use code :
class A :
def __init__(self) :
self.__content = []
def __add__(self, x) :
self.__content.append(x)
def __getattr__(self, attrname) :
if string.upper(attrname) == "FIRST" :
return self.__content[0]
elif string.upper(attrname) == "LAST" :
return self.__content[-1]
>>> a = A()
>>> a + 12
And it complains.
but when I substitute the __add__ with add(), it seems
right.
class A :
def __init__(self) :
self.__content = []
def add(self, x) :
self.__content.append(x)
def __getattr__(self, attrname) :
if string.upper(attrname) == "FIRST" :
return self.__content[0]
elif string.upper(attrname) == "LAST" :
return self.__content[-1]
>>> a = A()
>>> a.add(12)
>>> a.add(16)
>>> a.first
12
>>> a.last
16
----------------------------------------------------------------------
>Comment By: Raymond Hettinger (rhettinger)
Date: 2004-01-07 14:46
Message:
Logged In: YES
user_id=80475
It will work for you if you either use new style classes or
define __coerce__:
class A(Object):
. . .
or
def __coerce__(self, other):
return (self, other)
Old style classes handle operator overloading a bit
differently. When the lhs is an instance and the rhs is a
number, it will first try to see if __coerce__ is defined.
Unfortunately, in your example, the __getattr__ definition
intercepts but does not handle the lookup for coerce.
On a separate note, there is no need to write
string.upper(attrname); the preferred style is attrname.upper().
----------------------------------------------------------------------
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=871378&group_id=5470
More information about the Python-bugs-list
mailing list