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

yipeiwu_com6年前Python基础

这篇文章主要介绍了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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django实现全文检索的方法(支持中文)

PS: 我的检索是在文章模块下 forum/article 第一步:先安装需要的包: pip install django-haystack pip install whoosh p...

Python 按字典dict的键排序,并取出相应的键值放于list中的实例

方法一: def dict_to_numpy_method1(dict): dict_sorted=sorted(dict.iteritems(), key=lambda d:d[...

py中的目录与文件判别代码

>>> import os          &...

Python MD5文件生成码

import md5 import sys def sumfile(fobj): m = md5.new() while True: d = fobj.read(8096) if not...

对python使用http、https代理的实例讲解

在国内利用Python从Internet上爬取数据时,有些网站或API接口被限速或屏蔽,这时使用代理可以加速爬取过程,减少请求失败,Python程序使用代理的方法主要有以下几种: (1)...