欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-11-06 12:40:26
1如果如图所示使用多重继承,我们将看到什么 2我们看到了基类被执行了两次Baseclass 3代码验证吧 4改进措施 5完美解决=基类执行了一次 6代码验证 参考:本文参考学习《Python3 Object Oriented Programming》,根据自己理解改编,Dusty Phillips ......

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

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

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

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

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改进措施

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

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

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

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 著

 

上一篇: 是爽死的

下一篇: 喂,兄弟