为了账号安全,请及时绑定邮箱和手机立即绑定

多继承;不能从 2 个父类调用函数

多继承;不能从 2 个父类调用函数

手掌心 2021-12-29 10:32:20
无法从 Python 3.7.2 中的 Child 类中的两个不同父类调用这两个函数我尝试调用默认构造函数以及用户定义的函数它只是从参数列表中调用第一个类函数。调用(Parent1, Parent2) 时调用Parent1 函数,调用(Parent2, Parent1) 时调用Parent2 函数。class Parent1():    def fun1(self):        print("Fun1 from Parent1")    def fun2(self):        print("Fun2 from Parent1")class Child1(Parent1):    def fun2(self):        print("Fun2 from Child1")obj1 = Child1()obj1.fun1()obj1.fun2()print("========Block========")class Parent2():    def fun1(self):        print("Fun1 from Parent2")class Child2(Parent1, Parent2):    def fun1(self):        super().fun1()        print("Fun1 from Child2")obj2 = Child2()obj2.fun1()print("========Block========")class Child3(Parent2, Parent1):    def fun1(self):        super().fun1()        print("Fun1 from Child3")obj3 = Child3()obj3.fun1()print("========Block========")class First(object):    def __init__(self):        super(First, self).__init__()        print("First")class Second(object):    def __init__(self):        super(Second, self).__init__()        print("Second")class Third(object):    def __init__(self):        super(Third, self).__init__()        print("Third")Third()
查看完整描述

1 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

  class Parent1():

        def fun1(self):

            print("Fun1 from Parent1")

        def fun2(self):

            print("Fun2 from Parent1")


    class Child1(Parent1):

        def fun1(self):        

            Parent1.fun1(self)

            print("Fun2 from Child1")


    class Parent2():

        def fun1(self):

            print("Fun1 from Parent2")


    class Child2(Parent1, Parent2):

        def fun1(self):

            Parent1.fun1(self)

            Parent2.fun1(self)

            print("Fun1 from Child2")


    print("========Block========")

    obj1 = Child1()

    obj1.fun1()

    obj1.fun2()

    print("========Block========")    

    obj2 = Child2()

    obj2.fun1()

    print("========Block========")

o/p


========Block========

Fun1 from Parent1

Fun2 from Child1

Fun2 from Parent1

========Block========

Fun1 from Parent1

Fun1 from Parent2

Fun1 from Child2

========Block========


查看完整回答
反对 回复 2021-12-29
  • 1 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信