简体   繁体   English

如何直接访问组件的属性和方法?

[英]How to access attributes and methods of a component directly?

Having created a composite class in python, is there a (simple) way how to directly access the attributes/methods of the components?在 python 中创建了复合 class 后,是否有一种(简单)方法可以直接访问组件的属性/方法? That is without specifying which component the attribute/method belongs to?那是没有指定属性/方法属于哪个组件?

Here is the MWE:这是MWE:

class Component1:
    def __init__(self, data1):
        self.data1 = data1

    def add1(self):
        return self.data1 + 1

class Component2:
    def __init__(self, data2):
        self.data2 = data2

    def add2(self):
        return self.data2 + 2



class Composite:
    def __init__(self, data1, data2):
        self.component1 = Component1(data1)
        self.component2 = Component2(data2)


composite = Composite(data1, data2)

# Now I can access data1 (and data2)
# But it is really cumbersome
composite.component1.data1



# So I would like to have just
composite.data1

Is there a way to achieve this especially when the number of attributes and methods is high?有没有办法实现这一点,特别是当属性和方法的数量很多时? I know I could add the property我知道我可以添加该属性

@property
def data1(self):
    return self.component1.data1

but that would be painful with a high number of attributes and methods.但这对于大量的属性和方法来说会很痛苦。

Edit:编辑:

Each component has different attributes/method names from each other.每个组件都有彼此不同的属性/方法名称。 There also is not a common basis (eg, Component1().comp1_attibute_i or anything similar).也没有一个共同的基础(例如, Component1().comp1_attibute_i或任何类似的东西)。 The number at the end of the names is not present in the real problem (it was used just for simplification).名称末尾的数字在实际问题中不存在(它仅用于简化)。

Derive or use dictionaries for your class.为您的 class 派生或使用字典。 One dictionary has the attributes, and one dictionary the methods.一本字典有属性,一本字典有方法。

So attribute access is composite["data1"] .所以属性访问是composite["data1"]

Functions could be invoked via getattr .可以通过getattr调用函数。 I don't know the details but there's some useful stuff here .我不知道细节,但这里有一些有用的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM