Knowledge record: How does python process objects through the reflection mechanism?

Like Java's reflection mechanism, python can also obtain objects/functions and object attributes through reflection.

The method of use is also simpler than Java, and it is OK to directly obtain it through a fixed python built-in function.

Before starting, you first need to look at these four built-in functions in python, through which you can complete object processing.

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

Then, create a python class object TestCode, use reflection to get the object and process it.

# 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()))

Finally, use the main function of the python module to process the TestCode object we have created above through reflection.

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'))

After finishing the work, execute the main function call and find that all reflection executions have taken effect. The following is the data result printed after execution.

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

Python data visualization: word cloud image generation after data analysis!

Recommend windows command line software management tool WinGet, very convenient!

How to use the Selenium IDE browser plug-in to easily complete script recording and automate testing easily!

Guess you like

Origin blog.csdn.net/chengxuyuan_110/article/details/128620663