今天学习raise,参考网上代码写了一段自定义异常,遇到了另一个问题,代码如下:
# -*- coding:utf-8 -*-
#自定义
import traceback
class LengthRequiredException(Exception):
def __init__(self,length,minLength):
Exception.__init__(self)
self.length = length
self.minLength = minLength
l = [0,1,2,3]
minLength = 5
try:
if len(l) != minLength:
raise LengthRequiredException(len(l),minLength)
else:
pass
#except LengthRequiredException:
# print("Length not fit :length is %d required %d" %(LengthRequiredException(len(l),minLength).length,LengthRequiredException(len(l),minLength).minLength))
except LengthRequiredException as e:
print("Length not fit :length is %d required %d" %(e.length,e.minLength))
else:
print("no exception was raised")
finally:
print("finally over")
源码的except是 类 as e: ,我觉得原类名阅读性更好一些,就改成了类:,报错提示类没有length属性。搜索except,提示是捕捉对象的异常而不是类,于是我就将类实例化,(#注释那段)。 请问类 as e之后就有对象了么?实例化和有对象的区别是什么。
请举例简单例子说明,谢谢。
我理解的有对象是 A=类()
实例化是A=类(参数)
对
类
实例化的结果就是产生一个该类
的对象实例化是
action
对象是
value
class MyException(Exception):
pass
class ValidationError(Exception):
def __init__(self, message, errors):
# Call the base class constructor with the parameters it needs
super(ValidationError, self).__init__(message)
# Now for your custom code...
self.errors = errors
同学,你对面向对象基本概念和Python基本语法的掌握还有待加强啊。
将类进行实例化得到对象。
对象就是类进行实例化的产物
实例化就是由类得到对象的手段
至于你其他的问题,都是Python中基本语法问题,你应该自己去查看一下。