【发布时间】:2018-03-15 12:53:03
【问题描述】:
我正在模拟一组太阳能电池板(系统/容器)。该集群的属性几乎一对一地链接到元素的属性——面板(子系统/包含)——通过每个集群的元素数量。例如。集群的能源生产只是集群中的面板数量乘以单个集群的产量。成本、重量等也是如此。我的问题是如何将容器类链接到包含的类。
让我用一个简单的例子来说明:
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)
这看起来已经更“程序化”了,但可能还是太天真了。所以我想知道有哪些选择及其优缺点?
【问题讨论】: