[英]Python: derived classes access dictionary of base class in the same memory location
[英]Python combine derived classes to the same base class?
假設我有一個基礎 class Person
和兩個派生類Footballer
和Musician
。
顯然一個人既可以是足球運動員也可以是音樂家,所以也許我想要第三個 class 稱為FootballerAndMusician
,但是這個 class 將只是其他兩個類的組合(不會有沖突:兩個派生類只覆蓋一些特定的東西,並且Musician
中的任何內容都不會覆蓋Footballer
中覆蓋的內容,反之亦然)。
在 Python 中實現此模式的適當方法是什么,以避免在第三個 class 中的兩個派生類中重復代碼(想象一下,如果我必須對多個類執行此操作……)?
基本上,我想為Person
實現許多派生類,然后只要沒有沖突就可以輕松地將它們組合起來。
這在 Python 中是如何設計的?
這稱為多個 Inheritance,在 Python 中,它看起來像這樣
class FootballerAndMusician(Footballer, Musician):
# your specific class code goes here, like
現在 class 可以訪問兩個超類的所有方法。
查找方法的順序有一些微妙的復雜性。 然而,在這個簡單的例子中,它只是“從左到右”。 因此,如果Footballer
和Musician
都有一個名為play
的方法,那么在上面的示例中,您的FootballerAndMusician
將使用Footballer
版本。
請注意,多個 inheritance 會很快變得復雜和混亂,因此您應該謹慎使用它。 如果只是為了創建一些大的“分類法”,我建議避免使用它。
這很簡單:
class FootballerAndMusician(Footballer, Musician):
pass
當然,這假設Footballer
和Musician
(以及Person
)都被正確設計為允許多個 inheritance。 有關正確使用super
的建議,請參閱https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ 。
您正在尋找多個 inheritance。
Class Base1:
(body_1)
Class Base2:
(body_2)
Class Derived(Base1, Base2):
(body_3)
只要您的 Base Class Footballer
和Musician
不干擾其他人的方法,您就可以使用 go。
此外,如果您需要顯式使用構造函數,
Class Derived(Base1, Base2):
def __init__(self, args):
super(Derived, self).__init__(args)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.