1

Say I have a class:

class myM():
    def __init__(self):
        print("original")

I then instantiate this class a=myM() From which I can call a.__init__() However, if I use the class itself to call __init__, myM.__init__() results in an error.

These 2 options work however: myM.__init__(myM) and myM.__init__(a) where a=myM().

Question:

Why do I have to pass myM or a as an argument to __init__, for myM.__init__ to work?

Why dont I need to do that if I call a.__init__() instead?

alpha_989
  • 4,882
  • 2
  • 37
  • 48
  • 1
    In a nutshell: Because `self` is a required argument to `__init__`. On an instance that argument is pre-bound. As a plain class method, it is not. – deceze Jan 11 '18 at 14:04
  • @deceze, Thanks for your answer. I thought `self` was not recognized by python, but is a convention used by most python programmers. Is it that the first argument (if present, in a function definition inside a class) is prebound? Or does python look for the `self` argument? – alpha_989 Jan 11 '18 at 14:13
  • Also whats the difference between a class and a class method? Not sure who attached the `class method` answer.. but it doesnt seem to be related to what I asked here? – alpha_989 Jan 11 '18 at 14:14
  • 2
    The name "`self`" is just convention, the fact that the object instance gets passed as the first argument to methods is defined Python behaviour. And the duplicate is very very relevant; you need to understand what *bound* and *unbound* functions are to understand this behaviour. – deceze Jan 11 '18 at 14:16
  • @VisionN, thanks for the format change.. overlooked that mistake in formatting.. – alpha_989 Jan 11 '18 at 14:16
  • 1
    In another nutshell: `myM.__init__` is just a plain old function and it behaves exactly like a function: you don't pass the required first argument, it's going to raise an error. However, when you do `myM()`, that function gets bound and its first parameter is bound to be the instance you're creating with `myM()` (more or less, hand-waive hand-waive, read the duplicate about "descriptors"). – deceze Jan 11 '18 at 14:18
  • @deceze, thanks.. Read the thread.. Didnt know that this was related to unbound and bound methods. It makes sense now. In my opinion, a lot of newbies will have similar questions, but wont know the technical name to describe the problem using `bound` or `unbound` methods. As a result, they wont directly go to that thread. So it maybe better to open this question and leave an answer point to unbound/bound methods and why this is related to the other thread.. – alpha_989 Jan 11 '18 at 15:39
  • Well, it's already doing that. People can use your question as guide towards the answer. – deceze Jan 11 '18 at 15:44

0 Answers0