Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "self" convention __init__ vs method

Tags:

python

class MyClass(object):
   def __init__(self):
       self.var = "hi"

   def some_method(self):
       print self.var

#for the example below
myClass= MyClass()

So I understand that the following statements are equivelent.

myClass.some_method()
MyClass.some_method(myClass)

It takes object and passes it as the first argument self to some_method.

But when I do :

myClass= MyClass()

How does this flow work?

I am assuming its slightly different, and some magic happens behind the scenes (someone has some memory to allocate).

How does that translate to __init__(self) ? What is passed to __init__ MyClass ?

like image 609
Nix Avatar asked Jul 02 '11 13:07

Nix


2 Answers

myClass= MyClass() calls MyClass.__new__ method to create an instance of MyClass. After that MyClass.__init__ is called with this instance as first argument.

See the doc object.__new__:

object.__new__(cls[, ...])

Called to create a new instance of class cls.

object.__init__(self[, ...])

Called when the instance is created.

like image 183
Roman Bodnarchuk Avatar answered Oct 20 '22 05:10

Roman Bodnarchuk


__init__() method is called immediately after an instance of the class is created.

Dive into Python - Initializing and Coding Classes

like image 30
Kamil Avatar answered Oct 20 '22 04:10

Kamil