I have a multilevel inheritance (A->B->C). In base class i have a dictionary variable called "my_dict". From derived class, I am calling base class function by super().add_to_dict() to add some values.
Below code works as expected in python 3.7. But in Python 2.7.13 it throws error. can some one help me to fix it for 2.7.13?
from collections import OrderedDict
class A():
def __init__(self):
self.my_dict = OrderedDict()
def add_to_dict(self):
self.my_dict["zero"]=0
self.my_dict["one"]=1
class B(A):
def add_to_dict(self):
super().add_to_dict()
self.my_dict["two"]=2
def print_dict(self):
print("class B {}".format(my_dict))
class C(B):
def add_to_dict(self):
super().add_to_dict()
self.my_dict["three"]=3
def print_dict(self):
print("class C {}".format(self.my_dict))
obj = C()
obj.add_to_dict()
obj.print_dict()
Output ( 2.7.13):
File "test.py", line 15, in add_to_dict super().add_to_dict()
TypeError: super() takes at least 1 argument (0 given)
Output (python 3.7)
class C OrderedDict([('zero', 0), ('one', 1), ('two', 2), ('three', 3)])
In py2 you can use super(<Class>, <instance>).<function>()
. Those are also have to be "new style" classes. Those are defined by inheriting from object
.
So in your case proper code should be:
class A(object):
def __init__(self):
self.my_dict = OrderedDict()
def add_to_dict(self):
self.my_dict["zero"]=0
self.my_dict["one"]=1
class B(A):
def add_to_dict(self):
super(B, self).add_to_dict()
self.my_dict["two"]=2
def print_dict(self):
print("class B {}".format(my_dict))
class C(B):
def add_to_dict(self):
super(C, self).add_to_dict()
self.my_dict["three"]=3
def print_dict(self):
print("class C {}".format(self.my_dict))