#9 multiple __getattr__

closed-rejected
nobody
None
5
2003-12-10
2003-12-10
Chris Curvey
No

if I'm using a class that has multiple __getattr__
methods, spyce seems to always invoke the last one
defined. For example, if I have this class

class Foo:
def __init__(self):
self._name = "stupid class"
self._id = 1

def __getattr__(self, name):
return self._name

def __getattr__(self, id):
return self._id

and I have this spyce page

<%
import Foo

f = Foo.Foo()
%>
<html>
<body>
<%=f.name%> ! <%=f.id%>
<body>
</html>

I get "1 ! 1", instead of "stupid class ! 1", which I
would have expected.

Discussion

  • batripler
    batripler
    2003-12-10

    Logged In: YES
    user_id=371556

    Hi Chris,

    This is not a bug. It is the correct behaviour, as per the
    Python spec. The following code also prints out two '1's.

    class Foo:
    def __init__(self):
    self._name = "stupid class"
    self._id = 1

    def __getattr__(self, name):
    return self._name

    def __getattr__(self, id):
    return self._id

    f = Foo()
    print f.name
    print f.id

    The second method definition of __getattr__ is redefining the
    original implementation. If you would like to define a more
    meaningful __getattr__, please read:
    http://www.python.org/doc/2.2.3/ref/attribute-access.html
    The second parameter is a *STRING* containing the name of
    the attribute. The actual name of the parameter is not
    important.

     
  • batripler
    batripler
    2003-12-10

    • status: open --> closed-rejected
     
  • Chris Curvey
    Chris Curvey
    2003-12-10

    Logged In: YES
    user_id=129725

    (lightbulb goes on over my head)

    Yikes! I guess I've been misunderstanding how __getattr__
    works all these years. Sorry for the interruption, and
    thanks for the clue! (This also fixes something totally
    unrelated. Double bonus points!)