将 self 传递给 python 的构造函数

发布于 2024-09-28 01:39:48 字数 256 浏览 8 评论 0原文

我最近正在开发一个小型 python 项目,遇到了一种情况,我想将 self 传递到另一个对象的构造函数中。我不知道为什么,但我必须查一下这在 python 中是否合法。我已经在 C++ 和 Java 中做过很多次了,但我不记得曾经用 python 做过这个。

self 的引用传递给新对象是否不被视为 pythonic?我认为我没有见过任何 python 程序显式传递自引用。我只是碰巧直到现在才需要它吗?或者我正在以蟒蛇风格战斗?

I recently was working on a little python project and came to a situation where I wanted to pass self into the constructor of another object. I'm not sure why, but I had to look up whether this was legal in python. I've done this many times in C++ and Java but I don't remember ever having to do this with python.

Is passing references to self to new objects something that isn't considered pythonic? I don't think I've seen any python programs explicitly passing self references around. Have I just happen to not have a need for it until now? Or am I fighting python style?

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

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

发布评论

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

评论(2

花桑 2024-10-05 01:39:49

是的,它是合法的,是的,它是Pythonic的。

当您有一个对象和一个容器对象(其中所包含的对象需要了解其父对象)时,我发现自己使用此模式。

Yes it is legal, and yes it is pythonic.

I find myself using this pattern when you have an object and a container object where the contained objects need to know about their parent.

眉目亦如画i 2024-10-05 01:39:49

只需将其作为参数传递即可。当然,它不会在另一个初始化程序中被称为 self ...

class A:
    def __init__(self, num, target):
        self.num = num
        self.target = target

class B:
    def __init__(self, num):
        self.a = A(num, self)

a = A(1)
b = B(2)
print b.a.num # prints 2

Just pass it like a parameter. Of course, it won't be called self in the other initializer...

class A:
    def __init__(self, num, target):
        self.num = num
        self.target = target

class B:
    def __init__(self, num):
        self.a = A(num, self)

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