我在努力尋找一個「Python化」的方式下面的類組織:是否有對所需屬性(OOP)的「pythonic」方法?
我有在其構造函數初始化性能的基類,例如:
class Animal(object):
def __init__(self, class_, species, is_domesticated):
self.class_ = class_
self.species = species
self.is_domesticated = is_domesticated
然後,當我繼承,我想「硬編碼」一個或多個這些性質,如下所示:因此
class Mammal(Animal):
def __init__(self, species, is_domesticated):
Animal.__init__(self, 'Mammal', species, is_domesticated)
哺乳動物被實例化,像這樣:
monkey = Mammal('Primate', false)
問題是,我想使用* args,以便在更改基類定義時保留任何派生類。因此哺乳動物的定義變爲:
class Mammal(Animal):
def __init__(self, *args):
Animal.__init(self, *(args + (class_='Mammal',)))
哪個(不用說)看起來很可怕。一些提示將不勝感激=)
從'進口this':顯式優於隱式。我會說你的第一次嘗試看起來不錯! –
當你向它們也應該接受的基類中添加參數時,你並不是「僅僅離開派生類」。您只是通過不記錄參數來強化客戶端代碼作者。 –
也許你可以使用默認的可選參數(如'is_deomesticated = False' ...)? –