天天看點

69 - Python類是否支援多繼承,請舉例說明

Python是否支援多繼承,請舉例說明

  • Python支援多繼承
class Calculator:
    def calculator(self, expression):
        self.value = eval(expression)
        return self.value
    
    def printResult(self):
        print('result: {}'.format(self.value))
        
class MyPrint:
    def print(self, msg):
        print('msg: ', msg)
        
    def printResult(self):
        print('結果: {}'.format(self.value))
        
class MyCalculator1(Calculator, MyPrint):
    pass

class MyCalculator2(MyPrint, Calculator):
    pass

my1 = MyCalculator1()
print(my1.calculator('8 + 2 * 6'))
my1.print('hello')

my2 = MyCalculator2()
print(my2.calculator('1 + 1 * 1'))
my1.print('world')      
20
msg:  hello
2
msg:  world      

如果Python類的多個父類存在相同的成員,按着什麼規則處理

  • 如果多個分類存在沖突的成員,會使用最先遇到的成員
my1.printResult()

my2.printResult()      
result: 20
結果: 2