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

2018-06-18 02:22:55来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

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

3代码验证吧

class BaseClass:
    num_base_calls = 0
    def call_me(self):
        print("Calling method on Based Class")
        self.num_base_calls += 1
    
class LeftSubclass(BaseClass):
    num_left_calls = 0
    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 = 0
    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 = 0
    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改进措施

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

6代码验证

class BaseClass:
    num_base_calls = 0
    def call_me(self):
        print("Calling method on Based Class")
        self.num_base_calls += 1
    
class LeftSubclass(BaseClass):
    num_left_calls = 0
    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 = 0
    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 = 0
    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 著

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Flask路由报错:raise FormDataRoutingRedirect(request)

下一篇:python学习_常用语句