Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing self into a constructor in python

Tags:

python

this

self

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?

like image 765
Falmarri Avatar asked Oct 15 '10 20:10

Falmarri


People also ask

What is self in Python constructor?

Self is the first argument to be passed in Constructor and Instance Method. Self must be provided as a First parameter to the Instance method and constructor. If you don't provide it, it will cause an error.

What is __ init __( self in Python?

The self in keyword in Python is used to all the instances in a class. By using the self keyword, one can easily access all the instances defined within a class, including its methods and attributes. init. __init__ is one of the reserved methods in Python. In object oriented programming, it is known as a constructor.

Why do we pass self in Python?

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

Is __ init __ constructor?

The special method __init__ is the Python constructor. With an understanding of object oriented programming and classes, let's now look at how the __init__ method works within a Python program.


2 Answers

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.

like image 78
Nick Craig-Wood Avatar answered Oct 20 '22 15:10

Nick Craig-Wood


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
like image 29
Mike DeSimone Avatar answered Oct 20 '22 15:10

Mike DeSimone