延迟库允许打包函数访问多少信息?

发布于 2024-10-14 22:24:12 字数 328 浏览 2 评论 0原文

我知道,如果我推迟一个函数并向其传递一些参数,该函数就有这些参数并且可以使用它们,但是作为实例对象一部分的函数(例如)可以访问其对象的变量吗?

class foo (object):
    def __init__ (self):
        self.bar = 42
    def do_work (self):
        self.bar += 1

baz = foo()
deferred.defer(baz.do_work)

我基本上必须向函数提供它所需的所有信息作为参数吗?
另外,如果对 baz 的唯一引用是在延迟函数中,它会被丢弃吗?

I know that if I defer a function and pass some args to it, the function has those args and can work with them, but can a function that's part of an instanced object (for example) access the variables of its object?

class foo (object):
    def __init__ (self):
        self.bar = 42
    def do_work (self):
        self.bar += 1

baz = foo()
deferred.defer(baz.do_work)

Would I basically have to give the function all information it would need as arguments?
Also, would baz be trashed if the only reference to it were in a deferred function?

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

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

发布评论

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

评论(1

筱果果 2024-10-21 22:24:12

如果您传入实例方法(如代码示例中所示),则整个实例将被序列化并传递。您的 foo 对象引用的任何对象也将被序列化,依此类推。任何全局状态(例如,模块级别和类级别变量)都不会被保留,因此它将处于任务执行实例上这些变量所处的任何状态。

必要的数据在您调用 defer 时被序列化并发送到任务队列,因此如果这是您对 baz 的唯一引用,则 baz 的副本将立即被垃圾收集。但这不会阻止延迟任务运行,因为它会在反序列化并执行任务时创建一个新实例。

If you pass in an instance method, as you are in your code sample, the entire instance will be serialized and passed around. Any objects that your foo object refers to will also be serialized, and so forth. Any global state - for example, module level and class level variables - will not be preserved, so it'll be in whatever state those variables are on the instance the task executes on.

The necessary data is serialized and sent off to the task queue at the time you call defer, so if that was your only reference to baz, that copy of baz will be immediately garbage collected. That won't stop the deferred task from running, though, as it'll create a new instance when it deserializes and executes the task.

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