简体   繁体   English

包装对象的最佳pythonic方法是什么?

[英]What is the best pythonic way of wrapping an object?

I would like to be able to wrap any object in Python. 我希望能够在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 : 尝试使用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 . Alex Martelli班级班

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(). 您只是将变量self引用为wrap()中的某个对象。 When wrap() ends, that variable is garbage collected. 当wrap()结束时,该变量将被垃圾回收。

You could simply save the object in a Wrapper attribute to achieve what you want 您只需将对象保存在Wrapper属性中即可实现所需的功能

You can also do what you want by overriding new: 您还可以通过覆盖new来做您想做的事情:

class Wrapper(object):
    def __new__(cls, obj):
        return obj
t = Wrapper(list())
t.append(5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM