Here is a minimal example:
This works in both python 3.5 and 2.7:
class A(object):
def __init__(self, foo):
self._foo = foo
class B(A):
def __init__(self, foo):
A.__init__(self, foo=foo)
b = B(1)
Change line:
A.__init__(self, foo=foo)
to
A.__init__(self=self, foo=foo)
In python 3.5 works without problems, but in python 2.7 you will receive the following error:
Traceback (most recent call last):
File "self_key.py", line 9, in <module>
b = B(1)
File "self_key.py", line 7, in __init__
A.__init__(self=self, foo=foo)
TypeError: unbound method __init__() must be called with A instance as first argument (got nothing instead)
Is self as keyword argument forbidden in python 2.7 or is this a bug?
Update
I'm aware that python will use the first parameter of a bound function to pass the reference to the object from which has been called. I also know that the __init__
function expects that this parameter is an instance of the class. In this case A.__init__
is unbound so we must provide that parameter manually.
When I asked about self as keyword argument forbidden I'm speaking about self as "the first parameter of __init__
", which is supposed to receive a reference of the object to initialize. The name of the variable itself doesn't matter. We can perfectly change the name to this:, for example:
class A(object):
def __init__(this, foo):
this._foo = foo
class B(A):
def __init__(self, foo):
A.__init__(this=self, foo=foo)
b = B(1)
And it will be the same.
My question is why when calling the function we can perfectly specify that parameter as a positional argument (A.__init__(self, foo=foo)
) but when we try to pass it as a keyword argument (A.__init__(this=self, foo=foo)
) python 2.7 throws an error.