首页 > 编程语言 >反射机制--python

反射机制--python

时间:2023-08-02 20:44:06浏览次数:36  
标签:__ 反射 -- object python 导入 模块 attributes import

引用:

  https://www.cnblogs.com/vipchenwei/p/6991209.html

  https://www.cnblogs.com/vipchenwei/p/6991209.html

 

1.反射是什么:

  反射就是通过字符串的形式,导入模块;通过字符串的形式,去模块寻找指定函数,并执行。利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!

2.python反射中的内置函数:

  • getattr(object, name, [dafult value])
  • hasattr(object, name):
    说明:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的)
  • setattr(object, name, value)
  • delattr(object, name)

3.dir()说明:

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

4.反射应用:

import test as ss ss.f1() ss.f2() print(ss.a)

 我们要导入另外一个模块,可以使用import.现在有这样的需求,我动态输入一个模块名,可以随时访问到导入模块中的方法或者变量,怎么做呢?

  imp = input(“请输入你想导入的模块名:”) CC = __import__(imp) 這种方式就是通过输入字符串导入你所想导入的模块 CC.f1() # 执行模块中的f1方法

   上面我们实现了动态输入模块名,从而使我们能够输入模块名并且执行里面的函数。但是上面有一个缺点,那就是执行的函数被固定了。那么,我们能不能改进一下,动态输入函数名,并且来执行呢?

  #dynamic.py imp = input("请输入模块:") dd = __import__(imp) # 等价于import imp inp_func = input("请输入要执行的函数:") f = getattr(dd,inp_func,None)#作用:从导入模块中找到你需要调用的函数inp_func,然后返回一个该函数的引用.没有找到就烦会None f() # 执行该函数

  上面我们就实现了,动态导入一个模块,并且动态输入函数名然后执行相应功能。

  当然,上面还存在一点点小问题:那就是我的模块名有可能不是在本级目录中存放着。有可能是如下图存放方式:

  

  那么这种方式我们该如何搞定呢?看下面代码:

  dd = __import__("lib.text.commons") #这样仅仅导入了lib模块 dd = __import__("lib.text.commons",fromlist = True) #改用这种方式就能导入成功 # 等价于import config inp_func = input("请输入要执行的函数:") f = getattr(dd,inp_func) f()

标签:__,反射,--,object,python,导入,模块,attributes,import
From: https://www.cnblogs.com/nick-qiu/p/17601685.html

相关文章

  • (*)LeetCode 热题 100 之 238. 除自身以外数组的乘积
    题目给你一个整数数组nums,返回数组answer,其中answer[i]等于nums中除nums[i]之外其余各元素的乘积。题目数据保证数组nums之中任意元素的全部前缀元素和后缀的乘积都在32位整数范围内。请不要使用除法,且在O(n)时间复杂度内完成此题。示例1:输入:nums=......
  • 暑假集训D9 2023.8.2 补题
    A.「EZEC-10」排列排序给你一个长度为\(n\)的排列\(p_1,p_2,\cdots,p_n\)。你需要把它排序。每次可以花区间长度,即\(r-l+1\)的代价,选择排列中的任意一段区间\([l,r]\),并将\([l,r]\)从小到大排序。现在你可以让他进行若干次这个操作,直到\(p\)中元素的值从\(1\)到......
  • JS作用域
    全局作用域全局作用域变量:直接用var,const,let声明的变量局部作用域局部作用域变量:块,函数,对象,{}中声明的变量局部声明全局变量方法:JS中的作用域问题成为执行上下文,分为全局上下文和局部上下文JS中有一个概念作用域链(scopechain)表示上下文间的关系.和C++中的全局......
  • springboot 初始化加载过程 条件注解
    官网解释:https://docs.spring.io/spring-boot/docs/3.0.9/reference/html/features.html#features.developing-auto-configuration.condition-annotations从其他博客粘过来的表格:条件注解Condition处理类实例解释@ConditionalOnBeanOnBeanCondition@ConditionalOnBean(D......
  • ##英语中哪些地名前必须加the?
    英语中哪些地名前必须加the?在写作中总是分不清什么时候加the,直到最近看到一篇贴子。https://www.englishcurrent.com/grammar/definite-article-place-names-geography/把它翻译总结出来:1.大陆前不加the,海洋前加theAsia,EuropethePacific/thePacificOcean2.河海前......
  • 1588学习
    1)https://www.intel.cn/content/www/cn/zh/docs/programmable/683639/16-1/adding-the-external-time-of-day-module.html2.5.3.为具有1588PTP特性的实例添加外部Time-of-Day模块  2)https://www.intel.cn/content/www/cn/zh/docs/programmable/683639/16-1/implementing-a-......
  • acm模板
    二分查找l 对于满足条件最左边while(l<r){intmid=(l+r)/2;if(check(mid)){r=mid;}else{l=mid+1;}} l 对于满足条件最右边while(l<r){intmid=(l+r+1)/2;if(check(mid)){l=mid;}else{r=mid-1;}} l 对于不满足条件最左边while(l<r){intmid=(l......
  • nfls15095 Atcoder-abc123_d 蛋糕
    Atcoder-abc123_dAT小卖部从下学期开始售卖带有数字形状的蛋糕,\(X\),\(Y\)和\(Z\)种蛋糕分别带有\(1\)形,\(2\)形和\(3\)形蜡烛,而且每个蛋糕都有美味值,如下所示:带有\(1\)形蜡烛的美味值有:\(A_1,A_2,\cdots,A_X\)带有\(2\)形蜡烛的美味值有:\(B_1,B_2,\cdots,B_Y\)......
  • 配置Windows远程服务证书
    1、生成自签名证书$certname="certnameTest"##Replace{certificateName}$cert=New-SelfSignedCertificate-Subject"CN=$certname"-CertStoreLocation"Cert:\CurrentUser\My"-KeyExportPolicyExportable-KeySpecSignature-KeyLe......
  • 如何为你的 js 项目添加 ts 支持?
    前一段时间为公司内的一个JS公共库,增加了一些TypeScript类型支持。在这里简答记录一下。安装TypeScript依赖首先安装TypeScript依赖,我们要通过tsc指令创建声明文件:pnpminstall-Dtypescript创建配置文件接下来创建TypeScript配置文件:npxtsc--init这一......