Rewriting __getattr__

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jan 7 10:41:59 EST 2011


On 2011年1月07日 16:47:55 +0200, kost BebiX wrote:
> Well, actually the code you showed doesn't work)

Actually, it does. It just prints a warning message as well. Look 
carefully:
>>>> class A(object):
> .. def __init__(self):
> .. self.d = {}
> .. def __getattr__(self, key):
> .. try:
> .. return self.d[key]
> .. except KeyError:
> .. raise AttributeError
>>>> from copy import deepcopy
>>>> a = A()
>>>> deepcopy(a)
> Exception RuntimeError: 'maximum recursion depth exceeded while calling
> a Python object' in <type 'exceptions.AttributeError'> ignored 
> Exception RuntimeError: 'maximum recursion depth exceeded while calling
> a Python object' in <type 'exceptions.AttributeError'> ignored 
> 0: <__main__.A object at 0xda0250>

The last thing printed is the deepcopied object.
I've tested the above code in Python versions 2.4 through 3.2 and the 
only one that prints that message is 2.6.
-- 
Steven


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /