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

origin post:http://snipplr.com/view/35983/

  1. class DisneyCharacter():
  2. # This variable holds the name for the class DisneyCharacter
  3. name = “”
  4. class Duck():
  5. # This variable holds the name for the class Duck
  6. name = “”
  7. def __init__(self, name = None):
  8. “”” Constructor for the class Duck “””
  9. # If the user doesn’t specify a second name, “Duck” will be chosen
  10. if (name is None): name = “Duck”
  11. self.name = name
  12. def getName(self):
  13. “”” Returns the name stored in the class Duck “””
  14. return self.name
  15. def __init__(self, name = None, secondName = None):
  16. “”” Constructor for the class DisneyCharacter “””
  17. # If the user doesn’t specify a name, “Donald” will be chosen
  18. if (name is None): name = “Donald”
  19. # Creates a new instance of Duck
  20. newDuck = DisneyCharacter.Duck(secondName)
  21. # This will join together the names from the classes DisneyCharacter and Duck
  22. self.name = name + ” “ + newDuck.getName()
  23. def getName(self):
  24. “”” Returns the name stored in the class DisneyCharacter “””
  25. return self.name
  26. # Creates an instance of the class DisneyCharacter
  27. donald = DisneyCharacter()
  28. # Writes “Donald Duck”
  29. print(donald.getName())
  30. # Writes “Daisy Duck”
  31. daisy = DisneyCharacter(“Daisy”)
  32. print(daisy.getName())
  33. # Writes “Scrooge McDuck”
  34. unclescrooge = DisneyCharacter(“Scrooge”, “McDuck”)
  35. print(unclescrooge.getName())
|2|left
此条目发表在Python分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注