3

假设我正在使用某个 python 包中的一个类,如下所示

class foo(object):
    def __init__(self):
        self.a = None
        self.b = None
        self.c = None
        self.d = None
        self.e = None
        self.f = None

现在我需要在某些操作中使用类 foo 的对象 foobar 的属性bde,例如调用函数 qux :

print qux(foobar.b, foobar.d, foobar.e)

有什么方法可以创建它的简写版本,类似于以下想象的代码:

print qux(*foobar.[b,d,e])

注意约束:类和函数都不能改变。

4

2 回答 2

3

Well, getattr and setattr get you close:

Assignment with setattr (not needed for the next to work, just here for illustration):

class foo(object):
    def __init__(self):
        for name in 'abcdef':
            setattr(self, name, None)

Using values with getattr:

print qux(*(getattr(foobar, name) for name in 'bde'))

With normal, longer names you'd need to do in ['foo', 'bar'] instead.

于 2014-06-25T15:24:27.587 回答
1

既然你不能修改类,那么接受一个实例和任意数量的属性名称并返回一个元组的函数怎么样:

class Foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3


def getitems(obj, *items):
    values = []

    for item in items:
        values.append(getattr(obj, item))

    return tuple(values)

f = Foo()
print getitems(f, 'a', 'c')  # prints (1, 3)
qux(*getitems(f, 'a', 'c'))

如果您愿意修改类,您可以覆盖__getitem__以接受键元组。

class Foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

    def __getitem__(self, item):
        if isinstance(item, basestring):
            # treat single key as list of length one
            item = [item]

        values = []

        for key in item:
            # iterate through all keys in item
            values.append(getattr(self, key))

        return tuple(values)

f = Foo()
print f['a', 'c']  # prints (1, 3)
qux(*f['a', 'c'])
于 2014-06-25T15:28:30.270 回答