コードがあります。defaultdictを継承し、サブクラスメソッドでそのコピーメソッドを使用するにはどうすればよいですか?
from collections import defaultdict
class A(defaultdict):
def __init__(self):
super(A, self).__init__(lambda :0)
self.x = 1
def my_copy(self):
return self.copy()
if __name__ == '__main__':
a = defaultdict(lambda :0)
b = a.copy() # no error when using the base class directly
a = A()
b = a.my_copy()
エラーがあります:
Traceback (most recent call last):
File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1591, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py", line 1018, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/Users/liu/project/scir/pytorch_test/t.py", line 14, in <module>
b = a.my_copy()
File "/Users/liu/project/scir/pytorch_test/t.py", line 8, in my_copy
return self.copy()
TypeError: __init__() takes 1 positional argument but 3 were given
私はコピー方法を継承する方法がわからないと、私は3引数を与える理由も分かりません。
これにより、OPが望んでいない可能性のある別の工場をユーザーが指定できるようになります。 –
@brunodesthuilliersが私の編集を参照してください。しかし、私の結論は、組込み型から安全に継承するのは難しいことです。 –