有代碼。如何繼承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看我的編輯。但是我的結論是:從內置類型安全地繼承很困難。 –