TypeError: super() takes at least 1 argument (0 given) error is specific to any python version?
Solution 1
Yes, the 0-argument syntax is specific to Python 3, see What's New in Python 3.0 and PEP 3135 -- New Super.
In Python 2 and code that must be cross-version compatible, just stick to passing in the class object and instance explicitly.
Yes, there are "backports" available that make a no-argument version of super()
work in Python 2 (like the future
library) but these require a number of hacks that include a full scan of the class hierarchy to find a matching function object. This is both fragile and slow, and simply not worth the "convenience".
Solution 2
This is because of version of python. Check your python version with [python --version] it might be 2.7
In 2.7 use this [ super(baseclass, self).__init__() ]
class Bird(object):
def __init__(self):
print("Bird")
def whatIsThis(self):
print("This is bird which can not swim")
class Animal(Bird):
def __init__(self):
super(Bird,self).__init__()
print("Animal")
def whatIsThis(self):
print("THis is animal which can swim")
a1 = Animal()
a1.whatIsThis()
> In 3.0 or more use this [ super().__init__()]
class Bird(object):
def __init__(self):
print("Bird")
def whatIsThis(self):
print("This is bird which can not swim")
class Animal(Bird):
def __init__(self):
super().__init__()
print("Animal")
def whatIsThis(self):
print("THis is animal which can swim")
a1 = Animal()
a1.whatIsThis()
Solution 3
You can use the future library to have a Python2/Python3 compatibility.
The super function is back-ported.
BPL
Updated on July 05, 2022Comments
-
BPL almost 2 years
I'm getting this error
TypeError: super() takes at least 1 argument (0 given)
using this code on python2.7.11:
class Foo(object): def __init__(self): pass class Bar(Foo): def __init__(self): super().__init__() Bar()
The workaround to make it work would be:
class Foo(object): def __init__(self): pass class Bar(Foo): def __init__(self): super(Bar, self).__init__() Bar()
It seems the syntax is specific to python 3. So, what's the best way to provide compatible code between 2.x and 3.x and avoiding this error happening?
-
Martijn Pieters over 7 yearsOh boy, but that implementation. Stack frame inspection and a full traverse of the namespaces of the MRO to find the context? I can't recommend actually using this.
-
Martijn Pieters over 7 yearsJust use
super(ClassName, self)
and repeat yourself a little. -
Mark Bolster almost 5 yearsWhy would you make Bird a subclass of animal in an otherwise reasonable answer?
-
Solomon Ucko over 4 years@MarkBolster How is that unreasonable?
-
Gary02127 over 4 years@SolomonUcko - I think he meant why make Animal a subclass of Bird instead of making Bird a subclass of Animal... The latter is more logical.
-
Viraj Wadate over 4 years@all this is just dummy example. But still I appreciate your suggestion.