Python 可选参数审查

Python Optional Parameters Censoring

我正在尝试为 class 创建一个 __init__() 函数。这是我陷入困境的一个例子。

class Names():
    """a class for storing a number of names"""

    def __init__(self, names): #names can be any sequence of strings
        """takes a sequence of names and puts them into a list"""
        self.name_list = []
        for element in names:
            self.name_list.append(element)

但是当我尝试时:

Names("John", "Bobby", "Sarah")   

我收到错误消息

TypeError: init() takes 2 positional arguments but 4 were given

有没有办法让它适用于任意数量的名称或名称序列?

当然可以。您需要使用 * 运算符来表示可变数量的参数。像这样:

class Names():
    """a class for storing a number of names"""

    def __init__(self, *names): #names is can be any sequence of strings
        """takes a sequence of names and puts them into a list"""
        self.name_list = list(names)

那么无论你输入多少名字都会被存储在name_list中。

>>> Names("John", "Bobby", "Sarah")
<__main__.Names instance at 0x102b1c0e0>

您可以通过为 class 提供自己的 __repr__ 方法来稍微美化一下。例如:

def __repr__(self):
    clsname = self.__class__.__name__
    namestr = ", ".join(repr(n) for n in self.name_list)
    return "{0}({1})".format(clsname, namestr)

然后:

>>> Names("John", "Bobby", "Sarah")
Names('John', 'Bobby', 'Sarah')

与其将名称作为参数传递,不如传递名称列表,那么您无需对 __init__() 方法进行任何更改

所以而不是

Names("John", "Bobby", "Sarah") 

使用

Names(["John", "Bobby", "Sarah"]) 

您的 init() 代码将正常工作。