What is the best pythonic way of wrapping an object?
I would like to be able to wrap any obj开发者_运维百科ect in Python. The following does not seem to be possible, would you know why?
class Wrapper:
def wrap(self, obj):
self = obj
a = list()
b = Wrapper().wrap(a)
# can't do b.append
Thank you!
Try with the getattr python magic :
class Wrapper:
def wrap(self, obj):
self.obj = obj
def __getattr__(self, name):
return getattr(self.obj, name)
a = list()
b = Wrapper()
b.wrap(a)
b.append(10)
Perhaps what you are looking for, that does the job you are looking to do, much more elegantly than you are trying to do it in, is:
Alex Martelli's Bunch Class.
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
# that's it! Now, you can create a Bunch
# whenever you want to group a few variables:
point = Bunch(datum=y, squared=y*y, coord=x)
# and of course you can read/write the named
# attributes you just created, add others, del
# some of them, etc, etc:
if point.squared > threshold:
point.isok = 1
There are alternative implementations available in the linked recipe page.
You're just referencing the variable self to be a certain object in wrap(). When wrap() ends, that variable is garbage collected.
You could simply save the object in a Wrapper attribute to achieve what you want
You can also do what you want by overriding new:
class Wrapper(object):
def __new__(cls, obj):
return obj
t = Wrapper(list())
t.append(5)
精彩评论