包装对象的最佳 Python 方式是什么?

发布于 2024-11-06 05:40:43 字数 196 浏览 1 评论 0 原文

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

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

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

谢谢你!

I would like to be able to wrap any object 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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

半葬歌 2024-11-13 05:40:43

尝试使用 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)

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)
扭转时空 2024-11-13 05:40:43

也许您正在寻找的,比您尝试做的更优雅的工作是:

亚历克斯·马泰利束类

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

链接的配方页面中有可用的替代实现。

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.

梦醒时光 2024-11-13 05:40:43

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

您可以简单地将对象保存在 Wrapper 属性中来实现您想要的

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

终难愈 2024-11-13 05:40:43

您还可以通过覆盖 new 来执行您想要的操作:

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

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文