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'>" -- http://mail.python.org/mailman/listinfo/python-list