B
Bruno Desthuilliers
David Ells a écrit :
An obvious solution would be to define "each one" of these magic methods
in a mixin class. Else, here's a Q&D but working solution :
class Test(object):
def _get_magic_attribute(self, name):
return "YADDA YADDA"
for _name in ('__len__', '__str__', '__repr__'):
exec "%s = lambda self, _name='%s' : " \
"self._get_magic_attribute(_name)" % (_name, _name)
del _name
For a cleaner version, you may want to use a custom metaclass, but that
seems a bit overkill to me.
In Python we have a wonderful facility for customizing attribute
access by defining __getattr__ or __getattribute__ in our classes.
Unfortunately (or perhaps fortunately, for reasons I don't know), this
facility only works for explicit attribute access, i.e. accessing
foo.bar. What I am in need of, for reasons I'll keep out of the
discussion for now, is a similar facility for implicit attribute
access, such as the call to foo.__len__ when something like len(foo)
is executed. I would like some way to customize access during these
implicit lookups without having to define each one in the class
myself. Essentially what I am looking for is a mechanism like
__getattribute__, only one that will work for these implicit lookups
to functions like __len__, __str__, __getitem__, and so on. Hopefully
my question makes sense.
An obvious solution would be to define "each one" of these magic methods
in a mixin class. Else, here's a Q&D but working solution :
class Test(object):
def _get_magic_attribute(self, name):
return "YADDA YADDA"
for _name in ('__len__', '__str__', '__repr__'):
exec "%s = lambda self, _name='%s' : " \
"self._get_magic_attribute(_name)" % (_name, _name)
del _name
For a cleaner version, you may want to use a custom metaclass, but that
seems a bit overkill to me.