python: understand super()

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值