简体   繁体   English

Python的简写,用于表示一组类属性的元组

[英]Python shorthand for a tuple of a set of class attributes

Say i am using a class from some python package that looks like the following 假设我正在使用一些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

Now I need to use attributes b , d , and e of object foobar of class foo in some operation, say call a function qux for instance: 现在我需要在某些操作中使用类foo的对象foobar的属性bde ,例如调用函数qux:

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

Is there any way to create a shorthand version of this, something like the following imagined code: 有没有办法创建这个的速记版本,如下面的想象代码:

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

Note the constraints: neither the class nor the function can be changed. 注意约束:类和函数都不能改变。

Well, getattr and setattr get you close: 好吧, getattrsetattr让你关闭:

Assignment with setattr (not needed for the next to work, just here for illustration): 使用setattr分配(下一次工作不需要,只是为了说明):

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

Using values with getattr : getattr使用值:

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

With normal, longer names you'd need to do in ['foo', 'bar'] instead. 使用正常的,更长的名称,你需要in ['foo', 'bar']

Since you can't modify the class, how about a function that takes an instance and any number of attribute names, and returns a tuple: 由于您无法修改类,因此获取实例和任意数量的属性名称的函数如何,并返回一个元组:

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'))

If you are willing to modify the class, you can override __getitem__ to accept a tuple of keys. 如果您愿意修改该类,则可以覆盖__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'])

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

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