使用dict访问Python中的类的嵌套实例 [英] Use a dict to access nested instances of classes in Python

查看:194
本文介绍了使用dict访问Python中的类的嵌套实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在嵌套类中定义属性,然后稍后使用字符串或字符串列表访问它.这是我要执行的操作的代码

I'm trying to define an attribute in a nested class and then access it later using a string or maybe a list of strings. Here's code for what I'm trying to do

class MyNestedClass(object):
    def __init__(self):
        self.att1 = 5.

class MyClass(object):
    def __init__(self):
        self.my_nested_inst = MyNestedClass()

my_inst = MyClass()

当我只有一个像这样的列表时,我想更改my_inst.my_nested_inst.att1的值:my_list = ['my_inst','my_nested_inst','att1'].

I want to change the value of my_inst.my_nested_inst.att1 when all I have is a list like this: my_list = ['my_inst','my_nested_inst','att1'].

如果我使用这个:

vars(vars(vars()[my_list[0]])[my_list[1]])[my_list[2]]

这可行,但是问题是我需要将其扩展到嵌套实例的任意深度.我想不出一个通过for循环实现此目的的好方法.任何帮助是极大的赞赏.

This works, but the problem is that I need to extend it to an arbitrary depth of nested instances. I can't figure out a good way to make this work with a for loop. Any help is greatly appreciated.

此外,请注意,已经很好地解决了在全局名称空间中将字符串转换为变量名的问题,但是似乎没有答案适用于此.

Also, note that converting a string to a variable name in the global namespace has been well addressed, but none of the answers seem to apply here.

我将尝试解释为什么要这样做,并让我知道我在解释方面做得不好.我正在使用scipy.optimize.fmin,并且我一直仅使用4个参数进行优化.但是,我现在想扩展我的优化代码以处理任意数量的参数,其中一些是嵌套在类/实例层次结构中几层的属性.我希望能够在顶层创建列表或字典,以告诉fmin如何解压缩用于设置嵌套属性的参数数组.

I'll try to explain why I'm doing this, and let me know if I do a poor job of explaining. I am using scipy.optimize.fmin, and I have been using only 4 parameters for optimzation. However, I now want to expand my optimization code to handle an arbitrary number of parameters, some of which are nested attributes several layers into the class/instance hierarchy. I want to be able to create a list or dictionary at the top level to tell fmin how to unpack the parameter array for setting the nested attributes.

推荐答案

您可以使用

You can use operator.attrgetter to get nested attributes by specifying an attribute name containing dots (requires Python 2.6+):

f = attrgetter('date.month')之后,呼叫f(b)返回b.date.month.

After f = attrgetter('date.month'), the call f(b) returns b.date.month.

为方便起见,您可以创建一对帮助函数:

For convenience, you can create a pair of helper functions:

def get_nested_attr(vars_dict, attrs):
    inst = vars_dict[attrs[0]]
    return operator.attrgetter('.'.join(attrs[1:]))(inst)

def set_nested_attr(vars_dict, attrs, value):
    setattr(get_nested_attr(vars_dict, attrs[0:-1]), attrs[-1], value)

这是一个完整的示例(已通过Python 2.7.2测试):

Here's a complete example (tested with Python 2.7.2):

import operator

class MyNestedClass(object):
    def __init__(self):
        self.att1 = 5.

class MyClass(object):
    def __init__(self):
        self.my_nested_inst = MyNestedClass()

def get_nested_attr(vars_dict, attrs):
    inst = vars_dict[attrs[0]]
    return operator.attrgetter('.'.join(attrs[1:]))(inst)

def set_nested_attr(vars_dict, attrs, value):
    setattr(get_nested_attr(vars_dict, attrs[0:-1]), attrs[-1], value)


my_inst = MyClass()
my_list = ['my_inst','my_nested_inst','att1']

assert(my_inst.my_nested_inst.att1 == 5.)
set_nested_attr(vars(), my_list, 10.)
assert(my_inst.my_nested_inst.att1 == 10.)

这篇关于使用dict访问Python中的类的嵌套实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆