473,785 Members | 2,756 Online
Bytes | Software Development & Data Engineering Community
+ 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__(sel f, 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.p y", 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__(sel f, 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.p y", line 23, in ?
print t
TypeError: 'str' object is not callable

So why? What is the principles?

Jun 22 '07 #1
7 2334
En Fri, 22 Jun 2007 00:30:43 -0300, Roc Zhou <ch*******@gmai l.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__(sel f, 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.a r>
wrote:
En Fri, 22 Jun 2007 00:30:43 -0300, Roc Zhou <chowro...@gmai l.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__(sel f, 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...@gmai l.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.a r>
wrote:
En Fri, 22 Jun 2007 00:30:43 -0300, Roc Zhou <chowro...@gmai l.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__(sel f, 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__(sel f, 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__.tes t 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*******@gmai l.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__(sel f, 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*******@gmai l.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__(sel f, 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__.tes t 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.h tml#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__(sel f, 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__.tes t 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__(s elf, "__repr__")

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

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

Jun 22 '07 #8

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

Similar topics

3
3360
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 trials, I added some print statements to debug stuff. The ones I added to __setattr__ work as expected, but the one in __getattr__ seems to get called just under 1000 times for every __getattr__ call! Something is obviously not right here - but...
15
5954
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 lisp-like linked list class as a subclass of list. The __iter__ seems to work as i'd like, by traversing the links, and the __repr__ seems to work properly for somethings but not others. The basic idea is that a list such as is converted to ]],...
7
3367
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 classes show the fully-qualified class name, and the memory address of the instance. If I want to implement a __repr__ that's reasonably "nice" to the
13
3499
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
4510
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, it get's intercepted *along with it's argument*, in the same manner as __getattr__ intercepts attributes references for attributes that don't exist. This doesn't quite work: >>> class Foo:
5
2412
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 hints why this is? Example: class decoratorTest(object):
0
913
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 __init__(self): self.x = 1 def __getattr__(self, attr_name):
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 __init__(self): self.x = 1 def __getattr__(self, attr_name): try:
4
3944
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 AttributeError('%s not found in A' % name) def __getattr__(self, name):
7
1710
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 Derived(Base): what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have
0
9643
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10147
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10087
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9947
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8971
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7496
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4046
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2877
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.