我希望能够做类似下面的事情
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 >>>
重载
__getitem__
special method :>>> 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 >>>
关于python - 一个类需要实现什么才能用作参数元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24144766/