13

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?

Falmarri
  • 47,727
  • 41
  • 151
  • 191
  • Um, few things are unpythonic *per se*, it's just that there are *usually* better approaches (whether on a design or implementation level). Your questions doesn't name the problem, so we can't judge whether your solution is any good. –  Oct 15 '10 at 20:38
  • Now that I think about it, I have to agree, this doesn't get done as much in Python as in e.g. Java. No idea why, though. – David Z Oct 15 '10 at 20:39
  • I don't know why people insist on saying "pythonic" when they simply mean "clean", but there's nothing inherently wrong with this. Just watch out for circular references and `__del__`. – Glenn Maynard Oct 15 '10 at 21:07

2 Answers2

18

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.

Nick Craig-Wood
  • 52,955
  • 12
  • 126
  • 132
  • Yeah I understand why you need to do it, but I'm just not sure why I haven't seen it done very much in python. – Falmarri Oct 15 '10 at 20:40
  • 1
    Possibly because python has a wicked set of polymorphic container types which in general are sufficient for all your needs? – Nick Craig-Wood Oct 15 '10 at 20:44
  • Can adapter pattern be considered one of the uses, I mean if we don't consider parameter to be passed as *self* but another object instance which has to be contained. – Ashish Oct 15 '10 at 21:14
  • @Nick - I’m pretty late to the party here, but please could you explain what you mean by polymorphic container types, and why they are relevant? – Jinglesting Oct 06 '19 at 17:09
4

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
Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96