python3 反射的四种基本方法解析

作者:小张的博客 时间:2023-10-25 16:04:39 

这篇文章主要介绍了python3 反射的四种基本方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下


class Person(object):  
 def __init__(self):
   pass
 def info(self):
   print('我是person类中的info方法')

1.getattr()方法

这个方法是根据字符串去某个模块中寻找方法


instantiation = reflect.Person()#先实例化
f = getattr(instantiation,'info')#使用getattr函数去寻找字符串的同名方法
f()#调用方法
输出结果:我是person类中的info方法

2.hasattr()方法

这个方法是根据字符串去判断某个模块中该方法是否存在


instantiation = reflect.Person()#先实例化
f = hasattr(instantiation,'info')
print(f)
输出结果:True

3.setattr()方法

这个方法是根据字符串去某个模块中设置方法


instantiation = reflect.Person()
f = setattr(instantiation,'exit','this is a exit method')
f2 = hasattr(instantiation,'exit')
print(f2)
输出结果就是True

4.delattr()方法

这个方法是根据字符串去某个模块中删除方法


instantiation = reflect.Person()#实例化
f = delattr(instantiation,'exit')
f = hasattr(instantiation,'exit')
print(f)
输出结果就是False

来源:https://www.cnblogs.com/Zhang-engineer/p/11160554.html

标签:python,3,反射,方法
0
投稿

猜你喜欢

  • 使用python的pandas库读取csv文件保存至mysql数据库

    2024-01-22 00:26:19
  • python机器学习之神经网络(一)

    2023-06-21 23:28:42
  • php pdo oracle中文乱码的快速解决方法

    2023-11-16 22:12:47
  • 数据库Oracle数据的异地的自动备份

    2010-07-27 13:28:00
  • Python单例模式实例分析

    2023-11-26 03:22:52
  • python logging日志模块原理及操作解析

    2022-10-30 02:44:31
  • win7下MySql 5.7安装配置方法图文教程

    2024-01-20 21:04:12
  • python 利用文件锁单例执行脚本的方法

    2021-11-08 08:05:38
  • Python之ThreadPoolExecutor线程池问题

    2022-03-24 10:25:00
  • Python django框架输入汉字,数字,字符生成二维码实现详解

    2022-12-13 00:23:24
  • MySQL中触发器的基础学习教程

    2024-01-15 21:21:11
  • Python 字符串处理特殊空格\\xc2\\xa0\\t\\n Non-breaking space

    2022-03-09 19:20:16
  • Python求矩阵的范数和行列式

    2023-05-01 19:54:49
  • python添加模块搜索路径方法

    2023-11-20 09:29:45
  • Python的SQLalchemy模块连接与操作MySQL的基础示例

    2024-01-20 07:37:13
  • 解决mysql8.0.19 winx64版本的安装问题

    2024-01-24 01:02:17
  • ASP XML操作类代码

    2011-03-08 10:47:00
  • php初始化对象和析构函数的简单实例

    2023-11-09 18:11:14
  • python使用正则表达式检测密码强度源码分享

    2022-06-26 15:54:42
  • Python如何爬取qq音乐歌词到本地

    2021-03-25 19:59:45
  • asp之家 网络编程 m.aspxhome.com