decorating container types (Python 2.4)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • timaranz@gmail.com

    decorating container types (Python 2.4)

    Hi,

    I have a container class A and I want to add functionality to it by
    using a decorator class B, as follows:

    class A(object):
    def __len__(self):
    return 5

    class B(object):
    def __init__(self, a):
    self._a = a

    def __getattr__(sel f, attr):
    return getattr(self._a , attr)

    def other_methods(s elf):
    blah blah blah

    I was expecting len(B) to return 5 but I get
    AttributeError: type object 'B' has no attribute '__len__'
    instead.
    I was expecting len() to call B.__len__() which would invoke
    B.__getattr__ to call A.__len__ but __getattr__ is not being called.
    I can work around this, but I am curious if anyone knows _why_
    __getattr__ is not being called in this situation.

    Thanks
    Tim

  • George Sakkis

    #2
    Re: decorating container types (Python 2.4)

    On Oct 11, 5:42 pm, timar...@gmail. com wrote:
    Hi,
    >
    I have a container class A and I want to add functionality to it by
    using a decorator class B, as follows:
    >
    class A(object):
    def __len__(self):
    return 5
    >
    class B(object):
    def __init__(self, a):
    self._a = a
    >
    def __getattr__(sel f, attr):
    return getattr(self._a , attr)
    >
    def other_methods(s elf):
    blah blah blah
    >
    I was expecting len(B) to return 5 but I get
    AttributeError: type object 'B' has no attribute '__len__'
    instead.
    I was expecting len() to call B.__len__() which would invoke
    B.__getattr__ to call A.__len__ but __getattr__ is not being called.
    I can work around this, but I am curious if anyone knows _why_
    __getattr__ is not being called in this situation.
    >
    Thanks
    Tim
    Unfortunately __getattr__ is not called for special attributes; I'm
    not sure if this is by design or a technical limitation. You have to
    manually delegate all special methods (or perhaps write a metaclass
    that does this for you).

    George

    Comment

    Working...