2 つの辞書を簡単にマージできるようにするために、「dict」クラスの「+」演算子をオーバーライドしたいと思います。
そんな感じ:
def dict:
def __add__(self,other):
return dict(list(self.items())+list(other.items()))
一般に、組み込みクラスの演算子をオーバーライドすることは可能ですか?
2 つの辞書を簡単にマージできるようにするために、「dict」クラスの「+」演算子をオーバーライドしたいと思います。
そんな感じ:
def dict:
def __add__(self,other):
return dict(list(self.items())+list(other.items()))
一般に、組み込みクラスの演算子をオーバーライドすることは可能ですか?
一言で言えば、いいえ:
>>> 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)
個人的には、私は気にせず、それを行うための無料の機能を持っているだけです.
dict のサブクラスを作成できます(@NPEが言ったように):
class sdict(dict):
def __add__(self,other):
return sdict(list(self.items())+list(other.items()))
site.py
独自のPython Shellを作成してみませんか?
次に例を示します。
#!/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'
これは次のようになります。
class MyDict(dict):
def __add__(self,other):
return MyDict(list(self.items())+list(other.items()))