我希望能够在Python中包装任何对象。以下似乎不可能,你知道为什么吗?
class Wrapper:
def wrap(self, obj):
self = obj
a = list()
b = Wrapper().wrap(a)
# can't do b.append
谢谢!
答案 0 :(得分:5)
尝试使用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)
答案 1 :(得分:1)
也许你正在寻找的,那就是你要做的工作,比你试图做的更优雅,是:
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
链接的食谱页面中有其他可用的实现。
答案 2 :(得分:0)
您只是将变量self引用为wrap()中的某个对象。当wrap()结束时,该变量被垃圾收集。
您只需将对象保存在Wrapper属性中即可实现您的目标
答案 3 :(得分:0)
你也可以通过覆盖新的来做你想做的事:
class Wrapper(object):
def __new__(cls, obj):
return obj
t = Wrapper(list())
t.append(5)