Python学习笔记-面向对象编程、with语句与自定义上下文管理器

1.定义一个类

class Player():
	# 类的名称规范上以大写字母开头
	def __init__(self,name,hp,occu):
		# 名字,血量,职业
		self.name=name
		# self表示该类实例化后实例本身。
		self.hp=hp
		self.occu=occu
	def print_role(self):
		print('%s:%s %s'%(self.name,self.hp,self.occu))
	def updateName(self,newname):
		self.name=newname

user1=Player('tom',100,'war')
user2=Player('jerry',90,'master')
user1.print_role()
user2.print_role()
user1.updateName('wangsihang')
user1.print_role()
user1.name=('aaa')
user1.print_role()

输出为:
在这里插入图片描述

2.继承与多态

class Monster():
	# 定义怪物类
	def __init__(self,hp=100):
		self.hp=hp
	def run(self):
		print('移动到某一个位置')
	def whoami(self):
		print('我是怪物父类')

class Animals(Monster):
	# 父类放入子类括号中
	def __init__(self,hp=10):
		self.hp=hp
		# 也可以写成 super().__init__(hp)

class Boss(Monster):
	# Boss类怪物
	def __init__(self,hp=1000):
		self.hp=hp
	def whoami(self):
	# 同名方法在运行过程中可能会有多种状态,这种属性称之为多态。
		print('我是Boss')

a1=Monster(200)
print(a1.hp)
print(a1.run())

a2=Animals(1)
print(a2.hp)
print(a2.run())

a3=Boss()
as.whoami()

print('a1的类型 %s' %type(a1))
print('a2的类型 %s' %type(a2))
print('a3的类型 %s' %type(a3))

print(isinstance(a2,Monster))
# 判断a2是否为Monster的子类

输出为:
在这里插入图片描述

3.with语句:异常与类的结合

3.1 with语句的意义

在Python中,我们在打开文件的时候,为了代码的健壮性,通常要考虑一些异常情况,比如:

try:
    ccfile = open('name.txt')
    content = ccfile.readlines()
    ccfile.close()
except IOError:
    log.write('no data read\n')

如果文件操作出现异常,则写一条错误日志。
考虑一种情况,如果文件打开成功,但readlines()调用失败,异常处理会立即跳转到except处执行,这样文件关闭就没有机会被执行到了。
一种解决办法就是将close()语句放到finally子句中去,finally的特点是不管有无异常,都会被执行到。

try:
	try:
		ccfile = open('name.txt')
        content = ccfile.readlines()
    finally IOError:
    	ccfile.close()
except IOError:
	log.write('no data read\n')

或者

fd=open('name.txt')
try:
    for line in fd:
        print(line)
except Exception:
    print('输出错误!')
finally:
    fd.close()

但是上面的语句很不优雅。可以使用with语句:

with open('name.txt')as f:
	for line in f:
		print(line)

下面我们来剖析一下with语句的结构

with context as var:
    with_suite
with语句:可以代替try...except...finally语句,使代码更加简洁;
context:通常是表达式,返回一个对象;
var变量:用来保存context返回的对象,可以是单个值或元组;
with_suite:使用变量var对context返回对象进行各种操作的代码段

使用with后不管with中的代码出现什么错误,都会进行对当前对象进行清理工作。 例如file的file.close()方法,无论with中出现任何错误,都会执行file.close()方法。

3.2 异常与类的结合

with只有特定场合下才能使用。这个特定场合只的是那些支持了上下文管理器的对象。
这个管理器就是在对象内实现了两个方法其中为__ enter __( ) 和 __ exit __( )。
参照3.1,open函数也是支持上下文管理器的对象。

__ enter __( ):在使用with语句时调用,上下文管理器在代码开始前调用,返回值与as后面的参数进行绑定。
__ exit __( ):会话管理器在代码块执行完成好后调用,在with语句完成时,对象销毁之前调用。

我们可以自己定义一个带with的方法。即自定义with语句。

class Testwith():
# 自定义with语句的类。
	def __enter__(self):
		# 上下文管理器
		print('run')
	def __exit__(self, exc_type, exc_val, exc_tb):
		# 上下文管理器
		print('exit')
		# exc_tb用于判断异常
		if exc_tb is None:
			print('正常结束')
		else:
			print('has error %s' %exc_tb)

with Testwith():
	print('Test is running')
	raise NameError('testNameError')
	# 使用raise语句自己触发异常

输出为:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值