Created
June 26, 2015 10:59
-
-
Save pmslavin/d95b499e565fb403be15 to your computer and use it in GitHub Desktop.
Deepcopy hook demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import copy | |
class Parent(object): | |
def __init__(self): | |
self.children = [] | |
def addChild(self, child): | |
self.children.append(child) | |
def reset(self): | |
self.children = [] | |
def __str__(self): | |
ret = "" | |
for idx, c in enumerate(self.children): | |
ret += "[{0}] {1}\n".format(idx+1, c) | |
return ret | |
class Child(object): | |
def __init__(self, name): | |
self.name = name | |
def __str__(self): | |
return "{0} {1} at {2:x}".format(self.__class__.__name__, self.name, id(self)) | |
class Unique(Child): | |
def __deepcopy__(self, memo): | |
return self | |
if __name__ == "__main__": | |
p = Parent() | |
p.addChild(Child("One")) | |
p.addChild(Child("Two")) | |
p.addChild(Child("Three")) | |
p.addChild(Unique("Unique")) | |
print("Original Parent has:") | |
print(p) | |
p2 = copy.deepcopy(p) | |
print("Copy Parent has:") | |
print(p2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output:
Note that the single
Unique
object created is present in both containers, such thatwill evaluate to
True
.