[英]Why is it not possible in python to have an objects method return a tuple as argument in a new objects __init__ method?
為什么不能讓對象方法在新的對象init方法中返回元組作為參數? 為什么以下代碼不起作用以及需要做什么才能使其起作用?
class AcceptsTupleOnInit:
def __init__(self,s,z):
self.s = s
self.z = z
class ReturnsTuple:
def return_tuple(self):
return ("1", "2")
r = ReturnsTuple()
a = AcceptsTupleOnInit(r.return_tuple())
AcceptsTupleOnInit
不接受元組作為參數; 它需要兩個獨立的 arguments。 您需要先解壓縮元組。
a = AcceptsTupleOnInit(*r.return_tuple())
或者,定義__init__
以接受一個元組
def __init__(self, t):
self.s = t[0]
self.z = t[1]
或者更好的是,定義一個額外的 class 方法來為您解包元組。
# usage:
# a = AcceptsTupleOnInit.from_tuple(r.return_tuple())
@classmethod
def from_tuple(cls, t):
return cls(t[0], t[1])
在這三種情況下,您有責任提供一個至少有 2 個值的元組。 __init__
的原始定義要求return_tuple
提供正好2 個元素的元組; 修改后的__init__
和 class 方法更靈活,將簡單地忽略其他元素。 這就是為什么我更喜歡原始的__init__
(它對它的要求和接受的內容很精確),它帶有一個可以根據需要清理輸入元組的 class 方法。 您可以選擇忽略t[2:]
,或者如果它們存在,您可以引發異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.