python 反射、动态导入

1. 反射

hasattr(obj,'name')            # 判断对象中是否含有字符串形式的方法名或属性名,返回True、False

getattr(obj,'name',None)   # 返回对象中的方法或属性: obj.name,如果没有此方法或属性,返回None

setattr(obj,'name',value)   # 设置对象中方法或属性的值: obj.name = value

delattr(obj,'name')            # 删除对象中的方法或属性

class A(object):
    age = 22
    def __init__(self,name):
        self.name = name
    def getname(self):
        print(self.name)

a = A('wang')
print(hasattr(a,'age')) # True 判断对象中是否有字符串形式的方法或属性名字。

setattr(a,'sex','man')  # 给a对象设置一个属性:sex = 'man'
print(a.sex)

func = getattr(a,'getname',None) # 获取a对象的一个方法:getname;如果没有这个方法,则为None
func()

delattr(a,'name')  # 删除a对象的age属性
try:
    print(a.name)
except:
    print('name is not exists any more')

2. 动态导入模块

转自:https://blog.csdn.net/xie_0723/article/details/78004649

# 转自: https://blog.csdn.net/xie_0723/article/details/78004649
# a  # 文件夹
# │a.py
# │__init__.py
# b  # 文件夹
# │b.py
# │__init__.py
# ├─c  # 文件夹
# │c.py
# │__init__.py
#
# # c.py 中内容
# args = {'a': 1}
# class C:
#     def c(self):
#         pass

# a.py导入c.py
import importlib
pa1 = importlib.import_module('b.c.c')  # 绝对导入
pa2 = importlib.import_module('.c.c',package='b') # 相对导入
pa1.args # 提取变量args
pa1.C    # 提取class C
pa1.C.c  # 提取class C的c方法

猜你喜欢

转载自www.cnblogs.com/wztshine/p/11872701.html
今日推荐