Python在不同的modu中使用dict和valuetypes str、int、attribute和nested attribute

2024-04-26 16:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模块(module2),它包含一个函数:

#module2
def get_items():
    return {'thing1': 'string_value',
            'thing2': 1,
            'thing3': 'self.foo1',
            'thing4': 'self.foo2.bar',
            'thing5': 'self.foo3.bar['some_key']'} 

可以看出,字典键是字符串,值包括字符串和整数,但也包括属性(即self.foo1)、嵌套属性(即self.foo2.bar)和作为字符串写入的嵌套属性(即self.foo3.bar['some_key'])中的dict引用。它们被写成字符串是因为module2的上下文中没有self,相反,我想将这个字典导入另一个模块(module1)并引用一些self。你知道吗

我知道我可以通过getattr(self, value.split('self.')[1]访问属性。 我设置了一个递归函数来获取嵌套属性,在下面的代码中称为“rgetattr”。你知道吗

我唯一搞不懂的是如何处理嵌套字典。你知道吗

具体来说,我希望有以下行为:

#module2
def get_items():
    return {'thing1': 'string_value',
            'thing2': 1,
            'thing3': 'self.foo1',
            'thing4': 'self.foo2.bar',
            'thing5': 'self.foo3.bar['some_key']'} 

#module1
Class my_class:
    def __init__(self, foo):
        self.foo = foo # Note that this foo is an object

        ### The following is how I would like the imported dictionary to look ###
        my_desired_dict = {'thing1': 'string_value',
                           'thing2': 1,
                           'thing3': self.foo1,
                           'thing4': self.foo2.bar
                           'thing5': self.foo3.bar['some_key']}

        ### The following is how I am attempting to achieve this ###
        import module2
        item_dict = module2.get_items()

        my_desired_dict = {}

        for i in item_dict:
            if type(item_dict[i])==str and item_dict[i].startswith('self.'):
                    variable = item_dict[i].split('self.')[1]
                    this_attr = rgetattr(self, variable)
            else:
                 this_attr = item_dict[i]
            my_desired_dict[i] = this_attr



    def rgetattr(obj, attr, *args):
        def _getattr(obj, attr):
            return getattr(obj, attr, *args)
        return functools.reduce(_getattr, [obj] + attr.split('.'))

我愿意将module2中的“属性引用字符串”更改为self.foo文件等等,如果有一种方法可以做到这一点而不触发名称错误。你知道吗


Tags: 字符串selfreturn属性foovaluedefbar