Python面向对象——多重继承大揭秘

1如果如图所示使用多重继承,我们将看到什么

Python面向对象——多重继承大揭秘

2我们看到了基类被执行了两次Baseclass

Python面向对象——多重继承大揭秘

3代码验证吧

class BaseClass:
    num_base_calls =def call_me(self):
        print("Calling method on Based Class")
        self.num_base_calls += 1
    
class LeftSubclass(BaseClass):
    num_left_calls =def call_me(self):
        BaseClass.call_me(self)
        print("Calling method on Left Subclass")
        self.num_left_calls += 1
        
class RightSubclass(BaseClass):
    num_right_calls =def call_me(self):
        BaseClass.call_me(self)
        print("Calling method on Right Subclass")
        self.num_right_calls += 1

class Subclass(LeftSubclass, RightSubclass):
    num_sub_calls =def call_me(self):
        LeftSubclass.call_me(self)
        RightSubclass.call_me(self)
        print("Calling method on Subclass")
        self.num_sub_calls += 1

s = Subclass()
s.call_me() 
print(s.num_sub_calls, s.num_left_calls, s.num_right_calls, s.num_base_calls)

4改进措施

Python面向对象——多重继承大揭秘

5完美解决=基类执行了一次

Python面向对象——多重继承大揭秘

6代码验证

class BaseClass:
    num_base_calls =def call_me(self):
        print("Calling method on Based Class")
        self.num_base_calls += 1
    
class LeftSubclass(BaseClass):
    num_left_calls =def call_me(self):
        # BaseClass.call_me(self)
        super().call_me()
        print("Calling method on Left Subclass")
        self.num_left_calls += 1
        
class RightSubclass(BaseClass):
    num_right_calls =def call_me(self):
        # BaseClass.call_me(self)
        super().call_me()
        print("Calling method on Right Subclass")
        self.num_right_calls += 1

class Subclass(LeftSubclass, RightSubclass):
    num_sub_calls =def call_me(self):
        # LeftSubclass.call_me(self)
        # RightSubclass.call_me(self)
        super().call_me()
        print("Calling method on Subclass")
        self.num_sub_calls += 1

s = Subclass()
s.call_me() 
print(s.num_sub_calls, s.num_left_calls, s.num_right_calls, s.num_base_calls)

参考:本文参考学习《Python3 Object Oriented Programming》,根据自己理解改编,Dusty Phillips 著

相关推荐