Advertisement
karlakmkj

References to other instances

Jan 4th, 2021
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. '''
  2. Classes can also have references to other instances of themselves. Consider this Person class, for example, that allows for an instance of a father and mother to be given in the constructor.
  3.  
  4. Create 3 instances of this class. The first should have the name "Mr. Burdell" with an age of 53.
  5. The second instance should have a name of "Mrs. Burdell" with an age of 53 as well.
  6. Finally, make an instance with the name of "George P. Burdell" with an age of 25. This final instance should also have the father attribute set to the instance of Mr. Burdell, and the mother attribute set to the instance of Mrs. Burdell. Finally, store the instance of George P. Burdell in a variable called george_p. (It does not matter what variable names you use for Mr. and Mrs. Burdell.)
  7. '''
  8.  
  9. class Person:
  10.     def __init__(self, name, age, father=None, mother=None):
  11.         self.name = name
  12.         self.age = age
  13.         self.father = father
  14.         self.mother = mother
  15.  
  16. #My code
  17. p1 = Person("Mr. Burdell", 53)
  18. p2 = Person("Mrs. Burdell", 53)
  19. george_p = Person("George P. Burdell", 25, p1, p2)
  20.  
  21. #Sample model answer that can be all done in one line
  22. #george_p = Person("George P. Burdell", 25, mother = Person("Mrs. Burdell", 53), father = Person("Mr. Burdell", 53))
  23.  
  24.  
  25. #The code below will let you test your code. It isn't used for grading, so feel free to modify it. As written, it should print George P. Burdell, Mrs. Burdell, and Mr. Burdell each on a separate line.
  26. print(george_p.name)
  27. print(george_p.mother.name)
  28. print(george_p.father.name)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement