【问题标题】:Why is it not possible in python to have an objects method return a tuple as argument in a new objects __init__ method?为什么在 python 中不可能有一个对象方法返回一个元组作为新对象 __init__ 方法中的参数?
【发布时间】:2020-03-06 11:52:45
【问题描述】:
为什么不能让对象方法在新对象 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())
【问题讨论】:
标签:
python
python-3.x
oop
object
tuples
【解决方案1】:
AcceptsTupleOnInit 不接受元组作为参数;它需要两个单独的参数。您需要先解压缩元组。
a = AcceptsTupleOnInit(*r.return_tuple())
或者,定义__init__ 以接受元组
def __init__(self, t):
self.s = t[0]
self.z = t[1]
或者更好的是,定义一个额外的类方法来为你解包元组。
# 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__ 和类方法更灵活,将简单地忽略其他元素。这就是为什么我更喜欢原始的__init__(它需要和接受什么是精确的),它带有一个可以根据需要清理输入元组的类方法。您可以选择忽略t[2:],也可以在它们存在时引发异常。