Advertisement
karlakmkj

Making copies

Jan 5th, 2021
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. class Person:
  2.     def __init__(self, name, eyecolor, age):
  3.         self.name = name
  4.         self.eyecolor = eyecolor
  5.         self.age = age
  6.  
  7. class Name:
  8.     def __init__(self, firstname, lastname):
  9.         self.firstname = firstname
  10.         self.lastname = lastname
  11.  
  12. myPerson1 = Person(Name("David", "Joyner"), "brown", 30)
  13. #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.
  14. #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.
  15. #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.
  16.  
  17. #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
  18. myPerson2 = Person(Name(myPerson1.name.firstname, myPerson1.name.lastname),
  19.                    myPerson1.eyecolor, myPerson1.age) #this way is better as it only myPerson2.firstname will modified now
  20. myPerson2.eyecolor = "blue"
  21. print(myPerson1.eyecolor)  #remains as brown
  22. print(myPerson2.eyecolor)  #will now be modified to blue
  23. myPerson2.name.firstname = "Vrushali"
  24. print(myPerson1.name.firstname)  #should remain as David
  25. print(myPerson2.name.firstname)  #will be modified as Vrushali
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement