473,242 Members | 3,171 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

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 2306
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
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
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
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
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
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
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
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
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
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
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
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...

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.