Python 入门 之 反射
1、反射 : (自省)
反射主要是指程序可以访问、检测和修改它本身状态或行为的一种能力(自省)。
Python面向对象中的反射:通过字符串的形式操作对象的相关属性。Python中的一切事物都是对象(都可以使用反射)
<1> getattr() 获取
<2> setattr() 设置
<3> hasattr() 判断是否存在
<4> delattr() 删除
(1)通过字符串操作对象的属性和方法
class A:
def __init__(self,name):
self.name = name
def func(self):
print("is A func")
a = A("rimo")
A.func()
print(a.name)
a.func()
(2)对象的角度使用反射
class A:
def __init__(self,name):
self.name = name
def func(self):
print("is A func")
a = A("rimo")
print(hasattr(a,"name")) # 返回 True就是说明name这个属性在对象a中存在
print(getattr(a,"name"))
f = getattr(a,"func")
f()
setattr(a,"age",18)
print(a.__dict__)
delattr(a,"name")
print(a.__dict__)
(3)类的角度使用反射
class A:
def __init__(self,name):
self.name = name
def func(self):
print("is A func")
a = A("rimo")
print(hasattr(A,"name"))
f = getattr(A,"func")
f(11)
(4)当前模块使用反射
def func():
print("is func")
# 当前模块:
print(globals()["func"])
import sys
o = sys.modules[__name__] # 获取当前模块名对应的对象
f = getattr(o,"func")
f()
(5)其他模块使用反射
import test # 导入模块
test.func()
o = globals()["test"]
getattr(o,"func")()
(6)反射的应用场景
class Blog:
def login(self):
print("is login")
def register(self):
print("is register")
def comment(self):
print("is comment")
def log(self):
print("is log")
def log_out(self):
print("is log_out")
b = Blog()
func_dic = {
"1":b.login,
"2":b.register,
"3":b.comment,
"4":b.log,
"5":b.log_out
}
msg = """
1.登录
2.注册
3.评论
4.日志
5.注销
"""
choose = input(msg)
if choose in func_dic:
func_dic[choose]()
将上述代码进行修改,减少代码(通过字符串操作对象的属性和方法)
class Blog:
def login(self):
print("is login")
def register(self):
print("is register")
def comment(self):
print("is comment")
def log(self):
print("is log")
def log_out(self):
print("is log_out")
b = Blog()
msg = """
login
register
comment
log
log_out
"""
while 1:
choose = input(msg)
if hasattr(b,choose):
getattr(b,choose)()
else:
print("请重新输入!")