将 self 传递给 python 的构造函数
我最近正在开发一个小型 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,它是合法的,是的,它是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.
只需将其作为参数传递即可。当然,它不会在另一个初始化程序中被称为
self
...Just pass it like a parameter. Of course, it won't be called
self
in the other initializer...