Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
54
Task/Polymorphic-copy/Python/polymorphic-copy-1.py
Normal file
54
Task/Polymorphic-copy/Python/polymorphic-copy-1.py
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import copy
|
||||
|
||||
class T:
|
||||
def classname(self):
|
||||
return self.__class__.__name__
|
||||
|
||||
def __init__(self):
|
||||
self.myValue = "I'm a T."
|
||||
|
||||
def speak(self):
|
||||
print self.classname(), 'Hello', self.myValue
|
||||
|
||||
def clone(self):
|
||||
return copy.copy(self)
|
||||
|
||||
class S1(T):
|
||||
def speak(self):
|
||||
print self.classname(),"Meow", self.myValue
|
||||
|
||||
class S2(T):
|
||||
def speak(self):
|
||||
print self.classname(),"Woof", self.myValue
|
||||
|
||||
|
||||
print "creating initial objects of types S1, S2, and T"
|
||||
a = S1()
|
||||
a.myValue = 'Green'
|
||||
a.speak()
|
||||
|
||||
b = S2()
|
||||
b.myValue = 'Blue'
|
||||
b.speak()
|
||||
|
||||
u = T()
|
||||
u.myValue = 'Purple'
|
||||
u.speak()
|
||||
|
||||
print "Making copy of a as u, colors and types should match"
|
||||
u = a.clone()
|
||||
u.speak()
|
||||
a.speak()
|
||||
print "Assigning new color to u, A's color should be unchanged."
|
||||
u.myValue = "Orange"
|
||||
u.speak()
|
||||
a.speak()
|
||||
|
||||
print "Assigning u to reference same object as b, colors and types should match"
|
||||
u = b
|
||||
u.speak()
|
||||
b.speak()
|
||||
print "Assigning new color to u. Since u,b references same object b's color changes as well"
|
||||
u.myValue = "Yellow"
|
||||
u.speak()
|
||||
b.speak()
|
||||
7
Task/Polymorphic-copy/Python/polymorphic-copy-2.py
Normal file
7
Task/Polymorphic-copy/Python/polymorphic-copy-2.py
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import cPickle as pickle
|
||||
|
||||
source = {'a': [1, 2.0, 3, 4+6j],
|
||||
'b': ('string', u'Unicode string'),
|
||||
'c': None}
|
||||
|
||||
target = pickle.loads(pickle.dumps(source))
|
||||
8
Task/Polymorphic-copy/Python/polymorphic-copy-3.py
Normal file
8
Task/Polymorphic-copy/Python/polymorphic-copy-3.py
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
target = source.__class__() # Create an object of the same type
|
||||
if hasattr(source, 'items') and callable(source.items):
|
||||
for key,value in source.items:
|
||||
target[key] = value
|
||||
elif hasattr(source, '__len__'):
|
||||
target = source[:]
|
||||
else: # Following is not recommended. (see below).
|
||||
target = source
|
||||
Loading…
Add table
Add a link
Reference in a new issue