哪些数据模型方法实现参数关键字解包?

What data model methods implement argument keyword unpacking?

我有一个 class,我希望能够使用 *args**kwargs 语法将其解压缩到参数列表中。

class MyFoo:
    x = 1
    y = 2 # unpack x and y
    z = 3 # do not unpack z

def bar(x, y):
    print(x, y)

def baz(a, b=2, x=100, y=100, z=5):
    print(a, b, x+2, y+2, z)

foo = MyFoo()

bar(*foo) # should print "1 2"
baz(1, **foo) # should print "1 2 3 4 5"

我可以通过定义 __iter__:

来实现 *foo
def __iter__(self):
    return iter([self.x, self.y])

但是我一直无法弄清楚如何实施 **foo。需要实现什么方法来做到这一点?

我们只需要覆盖 keys 来获取要解包的属性的名称,然后 __getitem__ (最好作为类方法)来访问它们的值。检查以下内容:

class MyFoo(object):
  x = 1
  y = 2 # unpack x and y
  z = 3 # do not unpack z

  def __iter__(self):
      return iter([self.x, self.y])

  def keys(self):
      return ['x', 'y']

  @classmethod
  def __getitem__(cls, key):
    return cls.__dict__[key]



def bar(x, y):
  print(x, y)

def baz(a, b=2, x=100, y=100, z=5):
  print(a, b, x+2, y+2, z)

foo = MyFoo()

bar(*foo) # should print "1 2"
baz(1, **foo) # should print "1 2 3 4 5"