How can I inherit defaultdict and use its copy method in subclass method?

Viewed 3645

There is the code.

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()

There is the error:

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

I don't know how to inherit the copy method and also don't know why I give 3 argument.

3 Answers
Related