什么是最好的Python式包装方式?

2024-04-19 05:16:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想能够用Python包装任何对象。下面似乎不可能,你知道为什么吗?

class Wrapper:
    def wrap(self, obj):
        self = obj

a = list()
b = Wrapper().wrap(a)
# can't do b.append

谢谢!


Tags: 对象selfobjdefwrapperdocanlist
3条回答

尝试使用getattr python魔术:

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)

也许你所要寻找的,能做你想做的工作,比你想做的优雅得多,是:

Alex MartelliBunch 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

链接的配方页面中有其他可用的实现。在

您只是将变量self引用为wrap()中的某个对象。wrap()结束时,该变量被垃圾回收。在

您可以简单地将对象保存在包装器属性中以实现所需的效果

相关问题 更多 >