打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
知识记录:python如何通过反射机制处理对象?

和Java的反射机制一样,python也可以通过反射来获取对象/函数以及对象属性等。

使用方法也比Java更为简单,只需要通过固定的python内置函数来直接获取就OK了。

开始之前首先需要看一下python中内置的这四个函数,通过它们就能够完成对象的处理。

getattr函数:获取对象属性/对象方法
hasattr函数:判断对象是否有存在对应的属性及方法
delattr函数:删除指定的属性
setattr函数:为对象设置内容

然后,创建一个python类对象TestCode,使用反射的方式获取该对象并进行处理。

# It's importing the time module.
import time


class TestCode():
    def __init__(self):
        """
        A constructor. It is called when an object is created from a class and it allows the class to initialize the
        attributes of a class.
        """

        self.source_code = 'Python 集中营'
        self.source_tag = '公众号'

    def show_now_time(self):
        """
        It shows the current time.
        """

        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

最后,使用python模块的main函数通过反射的方式来处理我们上面已经创建好的TestCode对象。

if __name__ == '__main__':
    test_ = TestCode()
    # Checking if the object `test_` has the attribute `source_code`.
    if hasattr(test_, 'source_code'):
        # Printing the string `TestCode对象存在{}属性。` and replacing the `{}` with the string `source_code`.
        print('TestCode对象存在{}属性。'.format('source_code'))
        # Getting the attribute `source_code` from the object `test_`.
        source_code = getattr(test_, 'source_code')
        # Printing the string `TestCode对象source_code属性的值是:{}` and replacing the `{}` with the string `source_code`.
        print('TestCode对象source_code属性的值是:{}'.format(str(source_code)))

    # Setting the attribute `source_tag` of the object `test_` to the string `GONGZHONGHAO`.
    setattr(test_, 'source_tag''GONGZHONGHAO')

    # Deleting the attribute `source_code` from the object `test_`.
    delattr(test_, 'source_code')

    if hasattr(test_, 'source_code'):
        print('TestCode对象存在{}属性。'.format('source_code'))
    else:
        print('TestCode对象不存在{}属性。'.format('source_code'))

完事之后,执行main函数调用发现所有的反射执行都生效了,下面是执行后打印的数据结果。

TestCode对象存在source_code属性。
TestCode对象source_code属性的值是:Python 集中营
TestCode对象不存在source_code属性。

「Python 集中营」,只做知识分享 !

python数据可视化:数据分析后的词云图片生成!

推荐windows命令行软件管理工具WinGet,相当方便!

如何使用Selenium IDE浏览器插件轻松完成脚本录制,轻松搞定自动化测试!

使用python一起进入新年倒计时吧,可直接打包成exe应用!

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python函数 “大脑移植”
Python 自定义函数的特殊属性(收藏专用)
Python中60个内置函数的名称和功能
Python补充03 Python内置函数清单
Python开发基础总结(五)模块+日志+自省
python的多态与封装
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服