單獨繼承的語法:
class a: .... class b(a): ....
多重繼承的語法:
class a: .... class b: .... class c(a, b): ....
在繼承時,會用到父類別時,就可以透過super來呼叫方法或是傳遞建構式子
super方法能帶入參數為Type以及Object
而我們要判斷類別有沒有繼承關係可以透過issubclass去得知,第一個參數帶入子類別,第二個參數帶入父類別
class Animal: def __init__(self): self.name = "animal" def __init__(self, name): self.name = name def output(self): print(self.name, end = ' ') class Dog(Animal): def __init__(self, name): super(Dog,self).__init__(name) self.name = name animal = Animal("CY") animal.output() dog = Dog("is") dog.output() animal2 = Dog("dog") animal2.output() print("\n", issubclass(Dog, Animal)) print("\n", issubclass(Animal, Dog)) print("\n", issubclass(Animal, object))
參考資料:
http://docs.python.org/3/tutorial/classes.html#inheritance
http://docs.python.org/3/tutorial/classes.html#multiple-inheritance
http://docs.python.org/3/library/functions.html#super
http://docs.python.org/3/library/functions.html#type
http://docs.python.org/3/library/functions.html#issubclass