super() function allows the subclass to call the superclass methods explicitly, useful in inheritance.
note: there is some difference between python2 and python3 in use of super().
here is an example for python3:
class person:
def __init__(self,name,age):
print("this is __ini__ method in superclass \n")
self.name=name
self.age=age
def print_name(self):
print("this is print_name() from person calss \n")
print(self.name)
def print_age(self):
print("this is print_age() from person calss \n")
print(self.age)
class student(person):
def __init__(self,st_name,st_age,st_id):
super().__init__(st_name,st_age)
self.id=st_id
def print_name(self):
print("this is print_name() from student class \n")
super().__init__()
def get_id(self):
print("this is get_id() from student class \n")
return self.id
class group(student):
def __init__(self,grp_name,grp_age,grp_id,grp_sex):
print("this is __init__() from group \n")
super().__init__(grp_name,grp_age,grp_id)
print(super().get_id())
def get_sex(self):
return(self.sex)
if __name__=='__main__':
grp=group("xiaoming",12,'2018','M')
this is __init__() from group
this is __ini__ method in superclass
this is get_id() from student class
2018