Is there any way to create transparent wrapper objects in Python?
I thought implementing __getattribute_ _ on either the wrapper class or
its metaclass would do the trick, but it does not work for the built
in operators:
class Foo(object):
class __metaclass__(t ype):
def __getattribute_ _(self, name):
print "Klass", name
return type.__getattri bute__(self, name)
def __getattribute_ _(self, name):
print "Objekt", name
return object.__getatt ribute__(self, name)
[color=blue][color=green][color=darkred]
>>> Foo() + 1[/color][/color][/color]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'Foo' and 'int'[color=blue][color=green][color=darkred]
>>> Foo().__add__(1 )[/color][/color][/color]
Objekt __add__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 8, in __getattribute_ _
AttributeError: 'Foo' object has no attribute '__add__'
Thus, note that a + b does not do
try:
return a.__add__(b)
except:
return b.__radd__(a)
and neither, as I first thought
try:
return type(a).__add__ (a, b)
....
but something along the lines of
try:
return type.__getattri bute__(type(a), '__add__')(a, b)
....
So my naive implementation of a wrapper class,
class wrapper(object) :
def __init__(self, value, otherdata):
self.value = value
self.otherdata = otherdata
def __getattribute_ _(self, name):
return getattr(self.va lue, name)
does not work. Any ideas for a solution?
I thought implementing __getattribute_ _ on either the wrapper class or
its metaclass would do the trick, but it does not work for the built
in operators:
class Foo(object):
class __metaclass__(t ype):
def __getattribute_ _(self, name):
print "Klass", name
return type.__getattri bute__(self, name)
def __getattribute_ _(self, name):
print "Objekt", name
return object.__getatt ribute__(self, name)
[color=blue][color=green][color=darkred]
>>> Foo() + 1[/color][/color][/color]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for +: 'Foo' and 'int'[color=blue][color=green][color=darkred]
>>> Foo().__add__(1 )[/color][/color][/color]
Objekt __add__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 8, in __getattribute_ _
AttributeError: 'Foo' object has no attribute '__add__'
Thus, note that a + b does not do
try:
return a.__add__(b)
except:
return b.__radd__(a)
and neither, as I first thought
try:
return type(a).__add__ (a, b)
....
but something along the lines of
try:
return type.__getattri bute__(type(a), '__add__')(a, b)
....
So my naive implementation of a wrapper class,
class wrapper(object) :
def __init__(self, value, otherdata):
self.value = value
self.otherdata = otherdata
def __getattribute_ _(self, name):
return getattr(self.va lue, name)
does not work. Any ideas for a solution?
Comment