2

我有一个类,我希望能够使用*argsand**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"

我可以*foo通过定义来实现__iter__

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

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

4

1 回答 1

1

我们只需要重写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"
于 2018-04-05T15:04:28.830 回答