Skip to article frontmatterSkip to article content
Licence CC BY-NC-ND Thierry Parmentelat & Arnaud Legout

attributs et __getattr__

>>> echo = Echo()
>>> echo.foo()
'foofoofoo'
>>> echo.bar()
'barbarbar'
>>> echo.six()
'sixsixsix''

Indices

class Echo:
    def __getattr__(self, attrname):
        if len(attrname) == 3:
            # on pourrait écrire tripler()
            # mais pour inspecter ce qui nous est vraiment passé
            def tripler(*args, **kwds):
                # print("incoming", args, kwds)
                return attrname * 3
            return tripler
        else:
            raise AttributeError(f"No such method {attrname} length = {len(attrname)} != 3")
echo = Echo()
echo.foo()
'foofoofoo'
echo.bar()
'barbarbar'
try:
    echo.foobar()
except AttributeError as e:
    print("OOPS", e)
OOPS No such method foobar length = 6 != 3

Deuxième partie

Indices

>>> blacklist = [ 'six', 'two', 'four']
>>> echo2 = BlacklistEcho(blacklist)
>>> echo2.foo()
'foofoofoo'
>>> echo2.six()
... raise AttributeError
class BlacklistEcho(Echo):
    def __init__(self, blacklist):
        super().__init__()
        self.blacklist = blacklist
    def __getattr__(self, attrname):
        if attrname in self.blacklist:
            raise AttributeError("blacklisted method {attrname}")
        return super().__getattr__(attrname)
blacklist = [ 'six', 'two', 'four']

echo2 = BlacklistEcho(blacklist)

echo2.foo()
'foofoofoo'
try:
    echo2.six()
except AttributeError as e:
    print("OOPS", e)
OOPS blacklisted method {attrname}
try:
    echo2.foobar()
except AttributeError as e:
    print("OOPS", e)
OOPS No such method foobar length = 6 != 3