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()
Có lỗi:
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
Tôi không biết làm thế nào để kế thừa phương pháp sao chép và cũng không biết tại sao tôi cho 3 đối số.
Điều này cho phép người dùng chỉ định một nhà máy khác, có thể không phải là những gì OP muốn. –
@brunodesthuilliers xem chỉnh sửa của tôi. Nhưng kết luận của tôi là: thật khó để kế thừa một cách an toàn từ kiểu tích hợp. –