Python面向对象——多重继承大揭秘
1如果如图所示使用多重继承,我们将看到什么
2我们看到了基类被执行了两次Baseclass
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改进措施
5完美解决=基类执行了一次
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 著
相关推荐
huavhuahua 2020-11-20
xiaoseyihe 2020-11-16
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
meylovezn 2020-11-20
逍遥友 2020-11-20