博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
7、python类的定义和使用
阅读量:4111 次
发布时间:2019-05-25

本文共 796 字,大约阅读时间需要 2 分钟。

python中类的定义

(属性不可修改用_修饰)

class Player():    def __init__(self, name, hp, occr):        self.name = name        self.hp = hp        self.__occr = occr    def print_Method(self):        print("name is", self.name, "    hp is", self.hp,"    occr is", self.__occr)user2 = Player('tom', 100)user3 = Player('jerry', 80)user2.print_Method()user3.print_Method()

类的使用:with的使用

with open('name.txt') as f:    print(f.read())

自定义with的方法

class TestWith():    def __enter__(self):        print("start")    def __exit__(self, exc_type, exc_val, exc_tb):        if exc_tb is None:            print("stop")        else:            print('has error',exc_tb)    # 使用with TestWith():    print('to do something')    raise NameError('testNameError')

输出

start
to do something
has error <traceback object at 0x1045b8988>

转载地址:http://kkesi.baihongyu.com/

你可能感兴趣的文章
XML生成(一):DOM生成XML
查看>>
XML生成(三):JDOM生成
查看>>
Ubuntu Could not open lock file /var/lib/dpkg/lock - open (13:Permission denied)
查看>>
collect2: ld returned 1 exit status
查看>>
C#入门
查看>>
查找最大值最小值
查看>>
C#中ColorDialog需点两次确定才会退出的问题
查看>>
数据库
查看>>
nginx反代 499 502 bad gateway 和timeout
查看>>
linux虚拟机安装tar.gz版jdk步骤详解
查看>>
python猜拳游戏
查看>>
python实现100以内自然数之和,偶数之和
查看>>
python数字逆序输出及多个print输出在同一行
查看>>
ESP8266 WIFI数传 Pixhaw折腾笔记
查看>>
苏宁产品经理面经
查看>>
百度产品经理群面
查看>>
去哪儿一面+平安科技二面+hr面+贝贝一面+二面产品面经
查看>>
element ui 弹窗在IE11中关闭时闪现问题修复
查看>>
vue 遍历对象并动态绑定在下拉列表中
查看>>
Vue动态生成el-checkbox点击无法选中的解决方法
查看>>