小知识点:
动态导入模块:
# from socke import applicant as c
import importlib
# mod =__import__(‘socke.applicant‘)# 这是解释器自己内部用 mod相当于socke 一般不用,用下面的
mod=importlib.import_module(‘socke.applicant‘)#mod == applicant
mod.aa()
反射知识点:
反射:通过字符串映射或修改程序运行时的状态、属性、方法,有以下4个方法
getattr (object, name, default=None) # 获取字符串所映射的方法
hasattr (obiect, name) #判断一个obj对象里是否有对应的字符串str的方法
setattr(x, Y, v) #加字符串所反射的方法到对象里
delattr(x, y) del x.y
class Dog(object):
‘‘‘
This is dog class
‘‘‘
def __init__(self,name):
self.name = name
self.age =33
def eat(self):
print(" %s is eating"%self.name)
def run(self):
print(" %s is running"%self.name)
def sleep(self):
print(" %s is sleeping"%self.name)
def bulk(name):
print("%s is bulking"%name)
if __name__ == ‘__main__‘:
d = Dog(‘bb‘)
opt = input(">>:")
if hasattr(d,opt):
getattr(d,opt)()
# delattr(d, opt)
# getattr(d,opt)
# setattr(d,opt,‘leo‘)
else:
# setattr(d,opt,bulk)#在对象里加一个方法
# d.talk(d.name)
# setattr(d, opt, 3) #在对象里加一个属性
# print(getattr(d,opt))
print(d.name)
异常:
class MyException(Exception):
def __init__(self,msg):
self.msg =msg
def __str__(self):
# return self.msg
return ‘自定义异常:[%s]‘%self.msg
try:
print(‘try‘)
raise MyException(‘你傻了‘)
except MyException as e:
print( e)
except KeyError as e:
print("error1", e)
except IndexError as e:
print("error2", e)
except Exception as e:
print("未知错误",e)
else:
print("一切正常")
finally:
print("不管有没有错都执行")
断言:
作用:如果后面的程序很重要,一直行必须正确。先断言,只要错误就不执行后面。
a = "dsd"
try:
assert type(a) is str
print("断言成功")
except AssertionError as e:
print("断言失败",e)
‘‘‘
相当于
‘‘‘
if type(a) is str:
print("断言成功")
else:
print("断言失败")
原文:https://www.cnblogs.com/gtq7512/p/11438110.html