[issue8722] Documentation for __getattr__

Terry J. Reedy report at bugs.python.org
Thu Dec 7 21:12:48 EST 2017


Terry J. Reedy <tjreedy at udel.edu> added the comment:

Cheryl, thank you for reviving this, as it is still needed.  A slightly revised example better illustrates the claim in the doc revision about when __getattr__ is called.

class Foo(object):

    def __init__(self):
        self.foo = 1
        self.data = {"bing": 4}

    def __getattr__(self, name):
        print(f'Getting {name}')
        return self.data.get(name)

    @property
    def bar(self):
        return 3

    @property
    def bing(self):
        raise AttributeError("blarg")

f = Foo()
print('foo', f.foo)
print('__str__', f.__str__)
print('bar', f.bar)
print('bing', f.bing)
f.__getattribute__('bing')

# prints
foo 1
__str__ <method-wrapper '__str__' of Foo object at 0x0000016712378128>
bar 3
Getting bing
bing 4
Traceback (most recent call last):
  File "F:\Python\a\tem2.py", line 24, in <module>
    f.__getattribute__('bing')
  File "F:\Python\a\tem2.py", line 17, in bing
    raise AttributeError("blarg")
AttributeError: blarg

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue8722>
_______________________________________


More information about the Python-bugs-list mailing list