__repr__ affected after __getattr__ overloaded?

Discussion in 'Python' started by Roc Zhou, Jun 22, 2007.

  1. Roc Zhou

    Roc Zhou Guest

    Now I have to design a class that overload __getattr__, but after
    that, I found the __repr__ have been affected. This is a simple
    example model:

    #!/usr/bin/env python

    class test:
    def __init__(self):
    self.x = 1
    def __getattr__(self, attr_name):
    try:
    return self.__dict__[attr_name]
    except KeyError:
    self.__dict__[attr_name] = 'inexistent'
    return self.__dict__[attr_name]

    t = test()
    print t.x
    print t.y
    print type(t)
    T = t
    print T.x
    print t

    So far, I still want the "print t" return "<test instance at ...>",
    but when run, the result is:
    sh$ python test.py
    1
    inexistent
    <type 'instance'>
    1
    Traceback (most recent call last):
    File "testtree.py", line 23, in ?
    print t
    TypeError: 'str' object is not callable

    I also tried to overload __repr__, but no effect:
    #!/usr/bin/env python

    class test:
    def __init__(self):
    self.x = 1
    def __getattr__(self, attr_name):
    try:
    return self.__dict__[attr_name]
    except KeyError:
    self.__dict__[attr_name] = 'inexistent'
    return self.__dict__[attr_name]
    def __repr__(self):
    return 'test.__repr__'

    t = test()
    print t.x
    print t.y
    print type(t)
    T = t
    print T.x
    print t

    Still raise TypeError Exception:
    Traceback (most recent call last):
    File "testtree.py", line 23, in ?
    print t
    TypeError: 'str' object is not callable

    So why?

    Thanks
     
    Roc Zhou, Jun 22, 2007
    #1
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.