我不打算解释为什么多元组解包不是Python的一部分,但我要指出的是,在您的示例中,没有将类与数据匹配。在
您有以下代码:point = (1, 2)
size = (2, 3)
color = 'red'
class Rect(object):
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
但是更好的表达Rect对象的方法是:
^{pr2}$
一般来说,如果数据在元组中,请让构造函数获取元组。如果你的数据在dict中,让你的构造函数接受dict。如果你的数据是一个对象,让你的构造函数接受一个对象,等等
一般来说,您希望使用该语言的习语,而不是试图绕过它们。在
编辑
看看这个问题有多流行,我给你一个decorator,它允许你随意调用构造函数。在class Pack(object):
def __init__(self, *template):
self.template = template
def __call__(self, f):
def pack(*args):
args = list(args)
for i, tup in enumerate(self.template):
if type(tup) != tuple:
continue
for j, typ in enumerate(tup):
if type(args[i+j]) != typ:
break
else:
args[i:i+j+1] = [tuple(args[i:i+j+1])]
f(*args)
return pack
class Rect:
@Pack(object, (int, int), (int, int), str)
def __init__(self, point, size, color):
self.point = point
self.size = size
self.color = color
现在你可以用任何你喜欢的方式初始化你的对象。在r1 = Rect(point, size, color)
r2 = Rect((1,2), size, color)
r3 = Rect(1, 2, size, color)
r4 = Rect((1, 2), 2, 3, color)
r5 = Rect(1, 2, 2, 3, color)
虽然我不建议在实践中使用这种方法(它违反了只有一种方法的原则),但它确实证明了在Python中通常有一种方法可以做任何事情。在