Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Person:
- def __init__(self, name, eyecolor, age):
- self.name = name
- self.eyecolor = eyecolor
- self.age = age
- class Name:
- def __init__(self, firstname, lastname):
- self.firstname = firstname
- self.lastname = lastname
- myPerson1 = Person(Name("David", "Joyner"), "brown", 30)
- #Instead of referencing to myPerson1 at the same object (ie. myPerson2 = myPerson1), we can copy each attributes of myPerson1 so that we can modify the attributes separately.
- #Here we are constructing a new instance of a person and pass those immutable data types as arguments and letting myPerson2 has its own attributes.
- #myPerson2 = Person(myPerson1.name, myPerson1.eyecolor, myPerson1.age) # --> but this will also modify myPerson1's name because we have passed myPerson1.name as the argument of mutable type.
- #Therefore in order to copy another object (myPerson1) at an immutable level, we have to create a new instance of name for both firstname and lastname
- myPerson2 = Person(Name(myPerson1.name.firstname, myPerson1.name.lastname),
- myPerson1.eyecolor, myPerson1.age) #this way is better as it only myPerson2.firstname will modified now
- myPerson2.eyecolor = "blue"
- print(myPerson1.eyecolor) #remains as brown
- print(myPerson2.eyecolor) #will now be modified to blue
- myPerson2.name.firstname = "Vrushali"
- print(myPerson1.name.firstname) #should remain as David
- print(myPerson2.name.firstname) #will be modified as Vrushali
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement