Bad first argument given to super()
¶
super()
enables you to access the methods and members of a parent class without referring to the parent class by name. For a single inheritance situation the first argument to super()
should be the name of the current child class calling super()
, and the second argument should be self
(that is, a reference to the current object calling super()
).
Note
This anti-pattern only applies to Python versions 2.x, see “Super in Python 3” at the bottom of the page for the correct way of calling super()
in Python 3.x.
Anti-pattern¶
Python raises a TypeError
when it attempts to execute the call to super()
below. The first argument should be the name of the child class that is calling super()
. The author of the code mistakenly provided self
as the first argument.
class Rectangle(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
class Square(Rectangle):
def __init__(self, length):
# bad first argument to super()
super(self, Square).__init__(length, length)
s = Square(5)
print(s.area) # does not execute
Best practice¶
Insert name of child class as first argument to super()
¶
In the modified code below the author has fixed the call to super()
so that the name of the child class which is calling super()
(Square
in this case) is the first argument to the method.
class Rectangle(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
class Square(Rectangle):
def __init__(self, length):
# super() executes fine now
super(Square, self).__init__(length, length)
s = Square(5)
print(s.area) # 25
Super in Python 3¶
Python 3 adds a new simpler super()
, which requires no arguments. The correct way to call super()
in Python 3 code is as follows.
class Rectangle(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
class Square(Rectangle):
def __init__(self, length):
# This is equivalent to super(Square, self).__init__(length, length)
super().__init__(length, length)
s = Square(5)
print(s.area) # 25