Python反射

一 导入模块的三种方法:

方法一:也是最常用的方法:静态导入

In [15]: import random

In [16]: from random import randint

方法二: 使用内置的__import__函数

    函数介绍:这里还是推荐使用importlib.import_module()动态导入模块的

In [17]: help( __import__)

Help on built-in function __import__ in module builtins:

__import__(...)

__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module

Import a module. Because this function is meant for use by the Python

interpreter and not for general use it is better to use

importlib.import_module() to programmatically import a module.

The globals argument is only used to determine the context;

they are not modified. The locals argument is unused. The fromlist

should be a list of names to emulate ``from name import ...'', or an

empty list to emulate ``import name''.

When importing a module from a package, note that __import__('A.B', ...)

returns package A when fromlist is empty, but its submodule B when

fromlist is not empty. Level is used to determine whether to perform

absolute or relative imports. 0 is absolute while a positive number

is the number of parent directories to search relative to the current module.

    使用方法:

In [18]: __import__("random")

Out[18]: <module 'random' from 'c:\soft\python\lib\random.py'>

 

In [19]: __import__("django.core.files.uploadedfile")

Out[19]: <module 'django' from 'c:\soft\python\lib\site-packages\django\__init__.py'>

 

In [20]: __import__("django.core.files.uploadedfile", fromlist=True)

Out[20]: <module 'django.core.files.uploadedfile' from 'c:\soft\python\lib\site-packages\django\core\files\uploadedfile.py'>

注意: fromlist=True参数

方法三: 使用importlib.import_module()导入

在使用之前必须先导入importlib模块:

    In [23]: import importlib

 

In [24]: importlib.import_module("random")

Out[24]: <module 'random' from 'c:\soft\python\lib\random.py'>

 

In [25]: importlib.import_module("django.core.files.uploadedfile")

Out[25]: <module 'django.core.files.uploadedfile' from 'c:\soft\python\lib\site-packages\django\core\files\uploadedfile.py'>

 

二反射:

用于反射的4个内置函数getattr、hasattr、setattr、delattr

综合上上述的动态导入使用:

In [1]: m=__import__("random")

In [2]: hasattr(m,"randint")

Out[2]: True

In [3]: getattr(m,"randint")

Out[3]: <bound method Random.randint of <random.Random object at 0x000001DF4C18A9C8>>

In [7]: getattr(m,"randint")(1,20)

Out[7]: 9

In [8]: setattr(m,"name","ywhyme")

In [10]: m.name

Out[10]: 'ywhyme'

In [11]: delattr(m,"name")

In [12]: m.name

---------------------------------------------------------------------------

AttributeError Traceback (most recent call last)

<ipython-input-12-0634a6ce99cb> in <module>()

----> 1 m.name

AttributeError: module 'random' has no attribute 'name'

除此之外还可以用于现有对象进行反射

原文地址:https://www.cnblogs.com/twotigers/p/8215165.html