[英]How can I allow one or more arguments for initializing a class?
如果我想創建一個類,其中每個實例必須至少具有一個參數,但可以有更多參數。 如果沒有,則應引發異常。 我怎樣才能做到這一點?
您可以這樣編寫您的課程:
class MyClass(object):
def __init__(self, first, *rest):
# do something with the args
這將第一個參數作為first
一個參數,並將任何其他參數作為一個元組rest
。
kindall提出的解決方案是最Python化的方法:
class MyClass(object):
def __init__(self, first, *rest):
# do something with the args
每當您忘記第first
參數時,它將引發TypeError
。 如果希望引發自定義異常,請按以下步驟處理:
class MyClass(object):
def __init__(self, *args):
if not args:
raise MyCustomException()
first_arg = args[0]
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.