'how to define deep copy of subclass if super class has customized deep copy
My super class A has a method copy(), which is a customized deep copy function. The sub class B wants to inherit this deep-copy function while also deep-copying its own member and methods.
In the following explaining example, the copy function only copies the "A part" of B. My question is how can I modify the copy function in order to also deep-copy the member T and method addOn() and other potential class features?
class B(A):
def __init__(self, T):
super().__init__()
self.T = T
def addOn(self):
print("additional feature")
def copy(self):
return super().copy()
Solution 1:[1]
You've already made a good start, you just need to extend the subclass's copy function:
class B(A):
...
def copy(self):
new_b = super().copy() # new_b now has all the A stuff copied
new_b.T = however_you_copy_a_T_instance(self.T)
return new_b
Since addOn
is just a method, there is no need to copy it - it's implicitly part of any B instance.
As an aside, if you implement your class's copying functions as __copy__()
and __deepcopy__()
then your class will work properly with the built in copy and deepcopy stuff provided by https://docs.python.org/3/library/copy.html (See the end of that page for more info).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Erik |