【问题标题】:Linking container class properties to contained class properties将容器类属性链接到包含的类属性
【发布时间】: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)

这看起来已经更“程序化”了,但可能还是太天真了。所以我想知道有哪些选择及其优缺点?

【问题讨论】:

    标签: python oop facade getattr


    【解决方案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):
        ..
    

    我会将属性保留为单独的定义,因为您需要为所有属性编写单元测试(这样确定覆盖率会容易得多)。

    【讨论】:

    • 谢谢——我已经修正了这些语言错误:你可以说我是新手。
    • 欢迎使用 Python。如果您还没有这样做.. 在 python 提示符下尝试import this.. :-)
    • 我认为这个涉及继承的解决方案将类似于我给出的第一个示例:您编写(大部分)所有映射。这是一种明确的正确方法。我仍然对替代解决方案感到好奇。
    • 我要打印出 Python 之禅顺便说一句,在尝试做一些更复杂的事情之后,它现在更有意义了。
    猜你喜欢
    • 1970-01-01
    • 2015-02-12
    • 2013-04-05
    • 2019-01-13
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多