1.获取当前模块中的属性

class Person(object):

    def __init__(self,name,age):
        self.name = name
        self.age = age

p = Person('wdc',22)

import sys
q = sys.modules[__name__]   #获取模块本身,并赋值给q
if hasattr(q,'p'):  #查看当前模块下是否有名字叫“p”的属性
    print(getattr(q,'p'))   #获取当前模块的名字叫“p”的属性
print(p)    #打印p和上面做比较

python_反射——根据字符串获取模块中的属性

 

 

 打印输出后发现通过字符串获取的,和直接打印的模块相同。

 

 

2.从其他模块导入方法

  test_mod.py

def hi():
    print('Hi')

  test.py

import test_mod #导入其他模块
if hasattr(test_mod, 'hi'):  #判断test_mod模块是否有名字为“hi”的方法
    f = getattr(test_mod, 'hi')  #获去test_mod模块中名字叫“hi”的方法并赋值给f
    f() #执行获取的方法

    setattr(test_mod,'name','wdc')  #为方法添加名字为“name”的属性,并赋值为“wdc”
    print(test_mod.name)    #打印输出为模块添加的属性

python_反射——根据字符串获取模块中的属性

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-16
  • 2021-11-21
  • 2022-02-11
  • 2022-12-23
猜你喜欢
  • 2021-12-14
  • 2022-12-23
  • 2021-06-22
  • 2022-12-23
  • 2022-02-17
  • 2022-12-23
相关资源
相似解决方案