开发者

Passing self into a constructor in python

开发者 https://www.devze.com 2023-01-20 13:08 出处:网络
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 l

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 explic开发者_C百科itly passing self references around. Have I just happen to not have a need for it until now? Or am I fighting python style?


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消