oop_objvar.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. class Robot:
  2. """Represents a robot, with a name."""
  3. # A class variable, counting the number of robots
  4. population = 0
  5. def __init__(self, name):
  6. """Initializes the data."""
  7. self.name = name
  8. print "(Initializing {})".format(self.name)
  9. # When this person is created, the robot
  10. # adds to the population
  11. Robot.population += 1
  12. def die(self):
  13. """I am dying."""
  14. print "{} is being destroyed!".format(self.name)
  15. Robot.population -= 1
  16. if Robot.population == 0:
  17. print "{} was the last one.".format(self.name)
  18. else:
  19. print "There are still {:d} robots working.".format(
  20. Robot.population)
  21. def say_hi(self):
  22. """Greeting by the robot.
  23. Yeah, they can do that."""
  24. print "Greetings, my masters call me {}.".format(self.name)
  25. @classmethod
  26. def how_many(cls):
  27. """Prints the current population."""
  28. print "We have {:d} robots.".format(cls.population)
  29. droid1 = Robot("R2-D2")
  30. droid1.say_hi()
  31. Robot.how_many()
  32. droid2 = Robot("C-3PO")
  33. droid2.say_hi()
  34. Robot.how_many()
  35. print "\nRobots can do some work here.\n"
  36. print "Robots have finished their work. So let's destroy them."
  37. droid1.die()
  38. droid2.die()
  39. Robot.how_many()