封装

  1. class Player:
  2. def __init__(self, name, hp):
  3. # 属性
  4. self.__name = name # 私有
  5. self.hp = hp
  6. # 方法
  7. def print_role(self):
  8. print('%s: %d' % (self.__name, self.hp))
  9. def update_name(self, new_name):
  10. self.__name = new_name
  11. user1 = Player('tom', 100)
  12. user1.print_role()
  13. class Monster:
  14. pass # 不要报错
  15. # 输出
  16. tom: 100

继承/多态

  1. class Monster:
  2. def __init__(self, hp=100):
  3. self.hp = hp
  4. def run(self):
  5. print('run')
  6. def who_am_i(self):
  7. print('fu lei')
  8. class Animals(Monster):
  9. def __init__(self, hp=11):
  10. super().__init__(hp)
  11. class Boss(Monster):
  12. def __init__(self, hp=1000):
  13. super().__init__(hp)
  14. def who_am_i(self):
  15. print('boss')
  16. a = Animals()
  17. print(a.hp)
  18. a2 = Boss()
  19. a2.who_am_i()
  20. # 输出
  21. 11
  22. boss

根类

  • object