簡體   English   中英

Python可選參數檢查

[英]Python Optional Parameters Censoring

我正在嘗試為類創建__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 ()接受2個位置參數,但給出了4個

有沒有辦法使此功能適用於任意數量的名稱,或者換句話說就是名稱序列?

當然。 您需要使用*運算符來表示可變數量的參數。 像這樣:

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>

您可以通過為類提供自己的__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()代碼將正常運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM