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
?
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.
__init__()
method is called immediately after an instance of the class is created.
Dive into Python - Initializing and Coding Classes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With