防止不同类型的python fron结合类变量

发布于 2025-02-10 04:07:28 字数 808 浏览 0 评论 0 原文

我遇到了有趣的函数绑定行为:

class MyClass:
    def run(self):
        print(type(self))

class MyHelperClass:
    bar = MyClass.run

    def foo(self):
        self.bar()
        MyHelperClass.bar()

当我运行 myHelperClass()。foo()时,这发生了:

<class '__main__.MyHelperClass'>
# but run() isn't in this class

Traceback (most recent call last):
    ...
    MyHelperClass.bar()
TypeError: run() missing 1 required positional argument: 'self'
# this makes sense

类变量从 self 时,该类变量被绑定到 self >自我,即使类型不兼容?当我在班上访问它时,没有什么可绑定的,所以它是剩下的?

我能够防止该方法通过 bar = functools.partial(myclass.run)限制。

我对为什么绑定正确的理解吗?拥有无绑定功能的类VAR和标准实例方法之间是否有区别?

是否有更好的方法来防止该方法的限制,而不是 partial()

I ran across interesting function binding behavior:

class MyClass:
    def run(self):
        print(type(self))

class MyHelperClass:
    bar = MyClass.run

    def foo(self):
        self.bar()
        MyHelperClass.bar()

When I run MyHelperClass().foo(), this happens:

<class '__main__.MyHelperClass'>
# but run() isn't in this class

Traceback (most recent call last):
    ...
    MyHelperClass.bar()
TypeError: run() missing 1 required positional argument: 'self'
# this makes sense

The class variable gets bound to self when I access it from self, even though the type is incompatible? And when I access it on the class, there's nothing to bind to, so it's left unbound?

I was able to prevent the method from being bound by doing bar = functools.partial(MyClass.run).

Is my understanding of why it was bound correct? Is there even a difference between having class var that's an unbound function and a standard instance method?

Is there a better way to keep the method from being bound than partial()?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文