python - 一个类需要实现什么才能用作参数元组?

标签 python arguments

我希望能够做类似下面的事情

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”在实例上调用了什么?

最佳答案

有两种方法可以控制 * 操作符的行为:

  1. 重载 __iter__ special method :

    >>> 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
    >>>
    
  2. 重载 __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/

相关文章:

python - Pandas groupby 多列,多列列表

c# - nunit 中提供的参数数量错误

dart - 需要 1 个必需参数,但找到 0 个

python - 从字符串中读取数据,区分元素是数字还是数组

python - App Engine 应用程序设计问题

python - 通过比较两个列表来删除特定的单词

function - F# 函数参数类型注释不起作用

python - Django 1.4 SimpleListFilter 'selected' 选项问题

c++ - 如何在 c/c++ 中向参数添加选项? ( Visual Studio 平台2019)

javascript - 在 Javascript 中是否有等同于 .apply 的东西不会改变 this 的值?