鱼C论坛

 找回密码
 立即注册
查看: 3287|回复: 0

[技术交流] class类的学习

[复制链接]
发表于 2020-9-23 09:24:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
类(class)是面向对象的对同类型的事物的特征提取和归类,方便同类型的多次调用 下面看看类的定义的用法:
  1. class Player:  # Player首字母大写,这个不是规定,
  2.     # 是为了区别函数的规范,约定俗成,小写也行
  3.     def __init__(self, name, hp, occupation):  # __init__(self,*argv)是固定格式,
  4.         # class被调用时自动运行的函数,self是类的实例化后的自身
  5.         self.__name = name  # 这里加了两个下划线,就是类的封装,外部不能更改
  6.         # 只能通过方法来修改
  7.         self.hp = hp  # 变量称为属性,这里没有下划线,可以通过外部修改
  8.         self.occupation = occupation

  9.     def print_role(self):  # 定义一个方法,即类里面的其他函数
  10.         print("Player %s's hp: %s, %s" % (self.__name, self.hp, self.occupation))

  11.     def updatename(self, newname):
  12.         self.__name = newname


  13. class Monster:
  14.     '定义一个怪物类'
  15.     pass  # 定义之后不运行,这样不错提示错误


  16. user1 = Player('Tom', 100, 'warrior')  # 这是类的实例化
  17. user2 = Player('Jerry', 90, 'master')
  18. user1.print_role()
  19. user2.print_role()
  20. user2.hp = 95  # 直接通过外部修改
  21. print("Jerry's new hp:%s" % user2.hp)
  22. user1.updatename('Tommy')  # name属性封装后,只能通过方法来修改
  23. user1.print_role()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-27 14:59

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表