【发布时间】:2014-07-31 10:31:54
【问题描述】:
我希望能够执行以下操作
class C(object):
# I store a series of values in some way
# what do I need to implement to act like an array of arguments
c=C()
result=f(*c)
*"operator" 在这种用法中对实例调用了什么?
【问题讨论】:
我希望能够执行以下操作
class C(object):
# I store a series of values in some way
# what do I need to implement to act like an array of arguments
c=C()
result=f(*c)
*"operator" 在这种用法中对实例调用了什么?
【问题讨论】:
有两种方法可以控制* 运算符在这样使用时的行为:
>>> class C(object):
... def __init__(self, lst):
... self.lst = lst
... def __iter__(self):
... return iter(self.lst)
...
>>> def f(a, b, c):
... print "Arguments: ", a, b, c
...
>>> c = C([1, 2, 3])
>>> f(*c)
Arguments: 1 2 3
>>>
>>> class C(object):
... def __init__(self, lst):
... self.lst = lst
... def __getitem__(self, key):
... return self.lst[key]
...
>>> def f(a, b, c):
... print "Arguments: ", a, b, c
...
>>> c = C([1, 2, 3])
>>> f(*c)
Arguments: 1 2 3
>>>
【讨论】:
__getitem__)。
一种方法是继承tuple 或list。
【讨论】:
人们将此称为"positional expansion" 或参数解包。您的实例应提供__iter__ 方法,在迭代此对象时调用该方法。但是,我认为最干净的方法是继承collections.Iterable,即Python 中所有可迭代对象的抽象基类。
注意this 是关键字参数解包的同一个问题,要求对象是一个映射。
编辑:在这种情况下,我仍在尝试找到确切的实现,以查看哪个 C API 调用用于解包。这将产生这个问题的准确答案。有什么指点吗?
【讨论】: