471,328 Members | 1,890 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,328 software developers and data experts.

__repr__ affected after __getattr__ overloaded?

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

Jun 22 '07 #1
0 847

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Greg Brunet | last post: by
15 posts views Thread by Jim Newton | last post: by
7 posts views Thread by Ben Finney | last post: by
13 posts views Thread by Pelmen | last post: by
6 posts views Thread by Erik Johnson | last post: by
reply views Thread by Roc Zhou | last post: by
4 posts views Thread by Enrico | last post: by
7 posts views Thread by =?UTF-8?Q?Alexandru_Mo=C8=99oi?= | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.