PYTHON学习日子_DAY_1

2024-08-26 20:23:40 浏览数 (1)

2024/8/26

动态创建一个类

类是由TYPE 产生的

dog_class = type("Dog",(object,),{"role":dog})

创建一个Dog类,继承object, 属性 role = dog

def __init__(self,name,age):

self.name = name

self.age = age

dog_class = type("Dog",(object,),{"role":"dog","__init__":__init__})

d = dog_class('zss',25)

isinstance

isinstance(obj,cls)

检查obj是否是类cls的对象

class Foo(object):

pass

obj = Foo()

isinstance(obj,Foo)

issubclass(sub,super)

检查sub类是否是super类的派生类

class Super(object):

pass

class Sub(Super):

pass

issubclass(Sub,Super)

检测 可能发生的错误

try:

'''your code'''

except Exception:

'''上面的程序执行出错后就执行这里的代码'''

else:

'''没发生异常走这里'''

finally:

'''无论是否发生异常,都走这里'''

raise IndexError# 主动触发异常

while True:

num1 = input('num1:')

num2 = input('num2:')

try:

num1 = int(num1)

num2 = int(num2)

except Exception as e:

print('出现异常,信息如下:')

print(e)

Exception 万能异常

打印错误信息,e

强类型错误无法捕捉, 导致 程序崩溃例如: 缩进错误,语法错误

SyntaxError IndentationError

#自定义异常

class MyException(BaseException):#BaseException是所有异常的基类

def __init__(self,msg):

self.message = msg

def __str__(self):

return self.message

try:

raise MyException('错误')

except MyException as e:

print(e)

断言

assert语法用于判断代码是否符合执行预期

assert 1 1 == 3 # 结果为False 报错 AssertionError

0 人点赞