python反射
反射,可以实现去对象中操作成员(以字符串的形式去对象
中进行成员的操作)
class Person(object):
def __init__(self,name,wx):
self.name = name
self.wx = wx
def show(self):
message = "姓名{},微信:{}".format(self.name,self.wx)
user=Person("wxy",'123')
#获取成员
getattr(user,'name')#user.name
#调用成员方法
method=getattr(user,'show')()
#设置成员
setattr(user,'name','wxy1')
-
getattr,去对象中获取成员
v1=getattr(对象,'成员名称') v1=getattr(对象,'成员名称',不存在时默认值)
-
setattr,去对象中设置成员
setattr(对象,'成员名称',值)
-
hasattr,对象中是否包含成员
v1=hasattr(对象,'成员名称')
-
delattr,删除对象中的成员
delattr(对象,'成员名称')
应用案例
class Account(object): def login(self): print('login') def register(self): print('register') def index(self): print('index') def run(): name=input("请输入方法名:") account=Account() method=getattr(account,name,None) if not method: print("输入错误") return method() run()
由于反射支持以字符串的形式去对象中操作成员【等价于对象.成员】,所以,基于反射也可以对类,模块中的成员进行操作
以后遇到对象.成员,均可以基于反射来实现
1.一切皆对象
-
对象是对象
class Person(object): pass p=Person()
-
类是对象
class Person(object):
-
模块是对象
import re
2. import_module+反射
通过字符串的形式导入模块
示例一
from importlib import import_module
m=import_module('ramdom')#相当于import random
示例二
from importlib import import_module
m=import_module('requests.exceptions') #from requests import exceptions
实例三
from importlib import import_module
m=import_module('requests.exceptions.InvalidURL')#错误,只支持导入到模块
m=import_module('requests.exceptions')
m.InvalidURL #正确
很多源码中都会有import_module和getattr配合实现根据字符串的形式导入模块并获取成员【可以提高代码的重用性】