码迷,mamicode.com
首页 > 编程语言 > 详细

python super()函数

时间:2019-05-27 11:57:18      阅读:385      评论:0      收藏:0      [点我收藏+]

标签:角度   object   obj   self   例子   继承   构造方法   col   没有   

super()函数是用于调用父类的一个方法。举个例子:

执行下面代码时,会显示Son类没有属性money

class Father:
    def __init__(self):
        self.money = 1000class Son(Father):
    def __init__(self):
        self.age = 10

    def show_father_money(self):
        print(self.money)


a = Son()
a.show_father_money()  # 执行出错,显示 AttributeError: ‘Son‘ object has no attribute ‘money‘

所以如果没有用构造方法【__init__】初始化父类的值就无法调用相应属性,这时候我们可以将代码改为:

class Father(object):
    def __init__(self):
        self.money = 1000
class Son(Father):
    def __init__(self):
        Father.__init__(self)  # 调用父类构造函数
        self.age = 10

    def show_father_money(self):
        print(self.money)


a = Son()
a.show_father_money()  # 1000

这样就可以正常执行了,但是在实际运用中,由于子类继承的父类可能会改变名字,并且子类可能不止只继承一个父类,所以出于方便的角度考虑,我们就可以调用super()方法,super()方法通过MRO列表【可通过打印Son.mro()查看】来解决多重继承问题。super()可自动查询并执行MRO列表中父类相应的方法。

class GrandFather(object):
    def __init__(self):
        self.money1 = 1000


class Father(GrandFather):
    def __init__(self):
        super().__init__()
        self.money2 = 2000


class Son(Father):
    def __init__(self):
        super().__init__()
        self.age = 10

    def show_father_money(self):
        print(self.money1)
        print(self.money2)


a = Son()
a.show_father_money() # 1000 2000

 

python super()函数

标签:角度   object   obj   self   例子   继承   构造方法   col   没有   

原文地址:https://www.cnblogs.com/hwnzy/p/10929813.html

(0)
(1)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!