知识记录: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属性。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值