473,495 Members | 2,128 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

why __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 want the operation "print t" still return "<test instance
at ...>", but the reuslt 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__ itself:

#!/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

But the result remains:
Traceback (most recent call last):
File "testtree.py", line 23, in ?
print t
TypeError: 'str' object is not callable

So why? What is the principles?

Jun 22 '07 #1
7 2316
En Fri, 22 Jun 2007 00:30:43 -0300, Roc Zhou <ch*******@gmail.com>
escribió:
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:
You are creating many attributes with value "inexistent", even special
methods. Put a print statement and see what happens:
#!/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:
print "Now creating:",attr_name
self.__dict__[attr_name] = 'inexistent'
return self.__dict__[attr_name]
--
Gabriel Genellina

Jun 22 '07 #2
I know what's wrong. Thank you. And I think
try:
return self.__dict__[attr_name]
is unnecessary, because python will do it itself for us.

So now I have to overload __str__, but how can I make self.__str__
print as builtin str(): at here, I want get the result like:
<test instance at 0xb7bbb90c>
?

On 6 22 , 12 55 , "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
En Fri, 22 Jun 2007 00:30:43 -0300, Roc Zhou <chowro...@gmail.com>
escribió:
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:

You are creating many attributes with value "inexistent", even special
methods. Put a print statement and see what happens:
#!/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:

print "Now creating:",attr_name
self.__dict__[attr_name] = 'inexistent'
return self.__dict__[attr_name]

--
Gabriel Genellina

Jun 22 '07 #3
return hex(id(self))

On 6 22 , 1 48 , Roc Zhou <chowro...@gmail.comwrote:
I know what's wrong. Thank you. And I think
try:
return self.__dict__[attr_name]
is unnecessary, because python will do it itself for us.

So now I have to overload __str__, but how can I make self.__str__
print as builtin str(): at here, I want get the result like:
<test instance at 0xb7bbb90c>
?

On 6 22 , 12 55 , "Gabriel Genellina" <gagsl-...@yahoo.com.ar>
wrote:
En Fri, 22 Jun 2007 00:30:43 -0300, Roc Zhou <chowro...@gmail.com>
escribió:
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:
You are creating many attributes with value "inexistent", even special
methods. Put a print statement and see what happens:
#!/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:
print "Now creating:",attr_name
self.__dict__[attr_name] = 'inexistent'
return self.__dict__[attr_name]
--
Gabriel Genellina

Jun 22 '07 #4
I'm sorry but I still have a question, look at this example:
>>class test:
.... def __init__(self):
.... self.x = 1
.... def __getattr__(self, attr_name):
.... print attr_name
.... if attr_name == 'y':
.... return 2
.... else:
.... raise AttributeError, attr_name
....
>>t = test()
t.x
1
>>t.y
y
2
>>print t.x
1
>>print t
__str__
__repr__
<__main__.test instance at 0xb7f6d6cc>

Since __str__ and __repr__ does not exist because their names was
printed, why not the "AttributeError" be raised?
Jun 22 '07 #5
En Fri, 22 Jun 2007 02:48:50 -0300, Roc Zhou <ch*******@gmail.com>
escribió:
I know what's wrong. Thank you. And I think
try:
return self.__dict__[attr_name]
is unnecessary, because python will do it itself for us.
Exactly; by the time __getattr__ is called, you already know attr_name is
not there.
So now I have to overload __str__, but how can I make self.__str__
print as builtin str(): at here, I want get the result like:
<test instance at 0xb7bbb90c>
?
I would do the opposite: *only* create inexistent attributes when they are
not "special". This way you don't mess with Python internals.

.... def __getattr__(self, name):
.... if name[:2]!='__' or name[-2:]!='__':
.... self.__dict__[name] = 'inexistent'
.... return self.__dict__[name]
.... raise AttributeError,name

This way you don't create "fake" attributes for things like __bases__ by
example, and dir(), vars(), repr() etc. work as expected.

--
Gabriel Genellina

Jun 22 '07 #6
En Fri, 22 Jun 2007 03:43:26 -0300, Roc Zhou <ch*******@gmail.com>
escribió:
I'm sorry but I still have a question, look at this example:
>>>class test:
... def __init__(self):
... self.x = 1
... def __getattr__(self, attr_name):
... print attr_name
... if attr_name == 'y':
... return 2
... else:
... raise AttributeError, attr_name
...
>>>t = test()
t.x
1
>>>t.y
y
2
>>>print t.x
1
>>>print t
__str__
__repr__
<__main__.test instance at 0xb7f6d6cc>

Since __str__ and __repr__ does not exist because their names was
printed, why not the "AttributeError" be raised?
This is the implementation of str() in action; tries to find a __str__
method and fails; tries to find a __repr__ instead and fails; then uses
the default representation.
See <http://docs.python.org/ref/customization.html#l2h-179>

--
Gabriel Genellina

Jun 22 '07 #7
Roc Zhou wrote:
I'm sorry but I still have a question, look at this example:
>>>class test:
... def __init__(self):
... self.x = 1
... def __getattr__(self, attr_name):
... print attr_name
... if attr_name == 'y':
... return 2
... else:
... raise AttributeError, attr_name
...
>>>t = test()
t.x
1
>>>t.y
y
2
>>>print t.x
1
>>>print t
__str__
__repr__
<__main__.test instance at 0xb7f6d6cc>

Since __str__ and __repr__ does not exist because their names was
printed, why not the "AttributeError" be raised?
Because classic classes invoke

t.__getattr__(self, "__repr__")

and expect that to return a proper __repr__() method -- unless __getattr__()
raises an AttributeError:
>>class Test:
.... def __getattr__(self, name):
.... if name == "__repr__":
.... raise AttributeError
.... return "<inexistent %r>" % name
....
>>t = Test()
t
<__main__.Test instance at 0x401d42ac>

If you use newstyle classes you won't run into that particular problem:
>>class Test(object):
.... def __getattr__(self, name):
.... return "<inexistent %r>" % name
....
>>t = Test()
t
<__main__.Test object at 0x401d426c>
>>t.yadda
"<inexistent 'yadda'>"

Jun 22 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3334
by: Greg Brunet | last post by:
In adding the ability to refer to field values using dbfFile.field notation, I learned how to use __getattr__ and __setattr__ . After some trial and error, I got it working. But as part of my...
15
5924
by: Jim Newton | last post by:
hi all, does anyone know what print does if there is no __str__ method? i'm trying ot override the __repr__. If anyone can give me some advice it would be great to have. I have defined a...
7
3356
by: Ben Finney | last post by:
Howdy all, The builtin types have __repr__ attributes that return something nice, that looks like the syntax one would use to create that particular instance. The default __repr__ for custom...
13
3469
by: Pelmen | last post by:
How can I get rid of recursive call __getattr__ inside this method, if i need to use method or property of the class?
6
4494
by: Erik Johnson | last post by:
Maybe I just don't know the right special function, but what I am wanting to do is write something akin to a __getattr__ function so that when you try to call an object method that doesn't exist,...
5
2389
by: glomde | last post by:
Hi, I tried to write a decorator for that should be for methods but for some reasons it doens seem to work when you try to do it on the __getattr__ method in a class. Could anybody give some...
0
902
by: Roc Zhou | last post by:
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...
0
285
by: Roc Zhou | last post by:
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...
4
3910
by: Enrico | last post by:
Hi there, I have the following situation (I tryed to minimize the code to concentrate on the issue): def __getattr__(self, name): print 'A.__getattr__' if name == 'a': return 1 raise...
7
1700
by: =?UTF-8?Q?Alexandru_Mo=C8=99oi?= | last post by:
i'm facing the following problem: class Base(object): def __getattr__(self, attr): return lambda x: attr + '_' + x def dec(callable): return lambda *args: 'dec_' + callable(*args) class...
0
7120
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6991
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7160
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7196
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6878
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7373
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5456
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4897
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
286
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.