小编Mic*_*Liu的帖子

如何继承defaultdict并在子类方法中使用其copy方法?

有代码.

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()
Run Code Online (Sandbox Code Playgroud)

有错误:

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, …
Run Code Online (Sandbox Code Playgroud)

python collections inheritance copy defaultdict

7
推荐指数
2
解决办法
1225
查看次数

标签 统计

collections ×1

copy ×1

defaultdict ×1

inheritance ×1

python ×1