2017-10-04 57 views
0

我正在模擬太陽能電池板(系統/容器)的集羣。這個簇的屬性幾乎一對一地與元素的屬性 - 面板(子系統/包含的) - 通過每個簇的元素數相關聯。例如。集羣的能源生產僅僅是集羣中面板的數量乘以單個集羣的生產量。相同的成本,重量等我的問題是如何鏈接容器類到包含的類。將容器類屬性鏈接到包含的類屬性

讓我說明一個簡單的例子方法:

class PanelA(BasePanel): 
    ... _x,_y,_area,_production,etc. 

    @property 
    def production(self): 
     # J/panel/s 
     return self._area * self._efficiency 

    ... and 20 similar properties 

    @property 
    def _technical_detail 

class PanelB(BasePanel): 
    .... similar 

class PanelCluster(): 
    ....   
    self.panel = PanelA() 
    self.density = 100 # panels/ha 

    @property 
    def production(self): 
     # J/ha/h 

     uc = 60*60 # unit conversion 
     rho = self.density 
     production_single_panel = self.panel.production 

     return uc*rho*production_single_panel 

    ... and e.g. 20 similar constructions 

注意,在這種幼稚的做法一會寫例如20種這樣的方法看起來不符合這個DRY原則。

什麼是更好的選擇? (Ab)用途getattr

例如?

class Panel(): 
    unit = {'production':'J/panel/s'} 

class PanelCluster(): 
    panel = Panel() 

    def __getattr__(self,key): 

     if self.panel.__hasattr__(key) 
      panel_unit = self.panel.unit[key] 

      if '/panel/s' in panel_unit: 

       uc = 60*60 # unit conversion 
       rho = self.density 
       value_per_panel = getattr(self.panel,key) 

       return uc*rho*value_per_panel 
      else: 
       return getattr(self.panel,key) 

這已經看起來更「程序化」,但可能再次天真。所以我想知道它有哪些選擇和利弊?

回答

1

有一些Python的問題與您的代碼,如:

  • yield指特定Python中的東西,可能不是一個好標識符

,它的拼寫:

  • hasattr(self.panel.unit,key)
  • getattr(self.panel,key)

除此之外,您可能正在尋找一種涉及繼承的解決方案。也許PanelPanelCluster需要繼承PanelFunction類?

class PanelFunctions(object): 
    @property 
    def Yield(...): 
     ... 

class Panel(PanelFunctions): 
    .. 

class PanelCluster(PanelFunctions): 
    .. 

我將離開屬性separte定義,因爲你需要編寫單元測試所有的人(這將是更容易確定覆蓋這種方式)。

+0

謝謝 - 我修復了這些語言錯誤:你可以告訴我這是新的。 – balletpiraat

+0

歡迎來到Python。如果你還沒有這樣做..嘗試在python提示符處輸入this .. :-) – thebjorn

+0

我認爲這個涉及繼承的解決方案與我給出的第一個例子類似:你寫(大部分)全部映射出來。這是明確的適當方式。我仍然對替代解決方案感到好奇。 – balletpiraat