3

2 つの辞書を簡単にマージできるようにするために、「dict」クラスの「+」演算子をオーバーライドしたいと思います。

そんな感じ:

def dict:
  def __add__(self,other):
    return dict(list(self.items())+list(other.items()))

一般に、組み込みクラスの演算子をオーバーライドすることは可能ですか?

4

3 に答える 3

7

一言で言えば、いいえ:

>>> dict.__add__ = lambda x, y: None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'dict'

dict演算子を追加するには、サブクラス化する必要があります。

import copy

class Dict(dict):

  def __add__(self, other):
    ret = copy.copy(self)
    ret.update(other)
    return ret

d1 = Dict({1: 2, 3: 4})
d2 = Dict({3: 10, 4: 20})
print(d1 + d2)

個人的には、私は気にせず、それを行うための無料の機能を持っているだけです.

于 2013-10-16T13:29:22.413 に答える
3

dict のサブクラスを作成できます(@NPEが言ったように):

class sdict(dict):
    def __add__(self,other):
        return sdict(list(self.items())+list(other.items()))

よくわかりませんが、 の一部のオブジェクトを変更してみることができますsite.py。動作しません


独自のPython Shellを作成してみませんか?

次に例を示します。

shell.py

#!/usr/bin/env python

import sys
import os

#Define some variables you may need

RED = "\033[31m"

STD = "\033[0m"

class sdict(dict):
    def __add__(self,other):
        return dict(list(self.items())+list(other.items()))

dict = sdict

sys.ps1 = RED + ">>> " + STD
del sdict # We don't need it here!


# OK. Now run our python shell!
print sys.version
print 'Type "help", "copyright", "credits" or "license" for more information.'
os.environ['PYTHONINSPECT'] = 'True'
于 2013-10-16T13:33:13.220 に答える
1

これは次のようになります。

 class MyDict(dict):
     def __add__(self,other):
         return MyDict(list(self.items())+list(other.items()))
于 2013-10-16T13:31:34.133 に答える