python3在父类的方法中调用子类重写的方法

1.子类调用父类的方法,因此传入的self是<class ‘main.Child’>,因此,即使是在父类的方法中,子类的self调用的方法也是子类重写的方法

class Father():
    def func(self):
        print(self.__class__)
        print("Father")

    def test_father(self):
        print("Test_father", self.__class__)
        # 子类的self调用的方法也是子类重写的方法
        self.func()


class Child(Father):
    def func(self):
        print(self.__class__)
        print("Child")

    def test_child(self):
        # 子类的self是<class '__main__.Child'>
        print("Test_child", self.__class__)
        # 子类调用父类的方法
        self.test_father()


if __name__ == '__main__':
    tes_c = Child()
    tes_c.test_child()

输出为:

Test_child <class '__main__.Child'>
Test_father <class '__main__.Child'>
<class '__main__.Child'>
Child

2.使用super调用父类的方法,self仍然是子类的,因此调用的就是子类重写的方法

class Father():
    def __init__(self):
        self.x = 10

    def func(self):
        print(self.__class__)
        print("Father")
        self.test()

    def test(self):
        print(self.x, self.__class__)


class Child(Father):
    def __init__(self):
        self.x = 100
        # 调用父类的__init__重置self.x
        super(Child, self).__init__()

    def func(self):
        print(self.__class__)
        print("Child")
        # 子类的self调用父类的方法
        super().func()

    def test(self):
        print(self.x)


if __name__ == '__main__':
    tes_c = Child()
    tes_c.func()

输出为:

<class '__main__.Child'>
Child
<class '__main__.Child'>
Father
100
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值