反射reflect
什么是反射?
python的反射,它的本质其实就是用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,是一种基于字符串的事件驱动。
一、import和__import__():
区别:
import:用来导入.py文件(模块)、包括__init__.py文件,或者模块中的对象和属性。
__import__():传入的是字符串,__import__("package.module"),相当于from package from module。如果传入的字符串不是这种形式,
而是"package.子package.module",则也只会取前一个(即package,也就是import package)。那如果想取到,module怎么办,加入参数
fromlist = True。
我们来看一个示例:
文件目录结构如下:

在small_cat.py中:
aaaa = 1
test.py:
a = __import__("commons.cat") print(a)
执行结果:

可以看到,导入了commons包。
改写test.py,写成package.子package.module:
a = __import__("commons.cat.small_cat") print(a)
执行结果:

可以看到,即使写成了package.子package.module,仍然只对前面的commons进行了导入。
我们给__import__()加入fromlist参数,test.py如下:
a = __import__("commons.cat.small_cat",fromlist=True) print(a)
执行结果:

可以看到,这次讲small_cat模块导入进来了。
补充:若被导入的模块与当前模块属于同一个目录,则可以直接__import__(xx)
二、getattr():
def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass
getattr()的作用是:从一个对象中获取一个属性。getattr(x, 'y')等同于x.y,若给定了一个default值,则会在未找到属性时返回默认值。
a = __import__("commons.cat.small_cat", fromlist=True) v = getattr(a, 'aaaa')
上面例子中,导入了small_cat模块(该模块中有一个aaaa的变量,值为121),执行结果:121
三、hasattr():
def hasattr(*args, **kwargs): # real signature unknown """ Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError. """ pass
判断对象中是否存在属性。若存在返回True,反之返回False
浙公网安备 33010602011771号