【问题标题】:Overloading operators with dictionaries in Python在 Python 中使用字典重载运算符
【发布时间】:2015-04-28 05:50:39
【问题描述】:

我有一个 L 类,它接受多个这样的字典:

L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'))

我正在尝试将两个 D 对象相加并返回一个新的 L 对象,这样

a = L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'))
b = L((n:'morapple', t:'23', f:'44'),(m:'14', n:'132', p:'morecats'))
>> a+b
L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'),(n:'morapple', t:'23', f:'44'),(m:'14', n:'132', p:'morecats'))
c = (c:'carrot',d:'2')
>>a+c
L((k:'apple', y:'3', j:'4'),(k:'2', f:'12', q:'cats'),(c:'carrot',d:'2'))

我真的迷路了,到目前为止,我尝试使用 eval() 没有成功。它什么也没返回,我不知道该怎么办?

【问题讨论】:

  • 看起来添加两个DL 对象在语义上等同于将字典附加到列表中,对吗?

标签: python dictionary operator-overloading


【解决方案1】:

首先,远离eval() 使用它是非常非常少见的好主意。

其次,你为什么不能这样做:

def __add__(self, other):
    if type(other) == dict:
       return DL(*(self.dicts + [other]))
    elif type(other) == DL:
       return DL(*(self.dicts + other.dicts))
    raise ValueError("Only DL and dict are supported")

【讨论】:

  • 当我读到这篇文章时,我感到非常惊讶!虽然,self.dicts + other.dicts 将作为列表返回 - 我们的 DL 类采用 *args 并且不知何故需要采用逗号分隔的字典,这是我们使用 eval() 的原因
  • @unicornication:“逗号分隔”的字典是什么意思?您是存储字典还是 字符串表示 字典?
  • @DanielPryden 示例调用将是 DL(dict(blah),dict(blah), dict(blah)) - dicts 是使用*args 的逗号分隔参数的 x 个,我可以' t 想办法累积这些以传递给 DL() - 尽管 self.list_of_dictionaries... 是收集所有参数后创建的字典列表。
  • 构造函数接受多个 dict 参数,而不是单个 list-of-dicts 参数,因此 OP 需要类似 return DL(*self.dicts + [other])
  • 啊,你只需要DL(*(self.dicts + other.dicts)) -- 建立一个列表,然后将其作为参数传递。编辑:现在我看到@user4815162342 打败了我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 2013-03-21
相关资源
最近更新 更多