Nested classes: How to put a class inside another in Python


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. class DisneyCharacter():
  2.  
  3. # This variable holds the name for the class DisneyCharacter
  4. name = ""
  5.  
  6. class Duck():
  7.  
  8. # This variable holds the name for the class Duck
  9. name = ""
  10.  
  11. def __init__(self, name = None):
  12. """ Constructor for the class Duck """
  13. # If the user doesn't specify a second name, "Duck" will be chosen
  14. if (name is None): name = "Duck"
  15. self.name = name
  16.  
  17. def getName(self):
  18. """ Returns the name stored in the class Duck """
  19. return self.name
  20.  
  21. def __init__(self, name = None, secondName = None):
  22. """ Constructor for the class DisneyCharacter """
  23. # If the user doesn't specify a name, "Donald" will be chosen
  24. if (name is None): name = "Donald"
  25. # Creates a new instance of Duck
  26. newDuck = DisneyCharacter.Duck(secondName)
  27. # This will join together the names from the classes DisneyCharacter and Duck
  28. self.name = name + " " + newDuck.getName()
  29.  
  30. def getName(self):
  31. """ Returns the name stored in the class DisneyCharacter """
  32. return self.name
  33.  
  34. # Creates an instance of the class DisneyCharacter
  35. donald = DisneyCharacter()
  36.  
  37. # Writes "Donald Duck"
  38. print(donald.getName())
  39.  
  40. # Writes "Daisy Duck"
  41. daisy = DisneyCharacter("Daisy")
  42. print(daisy.getName())
  43.  
  44. # Writes "Scrooge McDuck"
  45. unclescrooge = DisneyCharacter("Scrooge", "McDuck")
  46. print(unclescrooge.getName())

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.