Python Reflect Example

Python provide hasattr(), getattr(), setattr() and delattr() function for us to verify ( hasattr() ), get ( getattr() ), set ( setattr() ) or delete ( delattr() ) objects properties. We can use these functions to implement reflect feature in python. This example will tell you how to use them.

1. Python Reflect Example Steps.

    1. Create a PyDev project in eclipse. You can read the article How To Run Python In Eclipse With PyDev.
    2. Create a python package com.dev2qa.example.reflect.
  1. Create two modules commons ( ) and visit ( ) in reflect package.
  2. Below is the source code.
    ''' Below functions are commons module attributes, you can use python built-in function getattr(commons, 'function_name_str') to get them and execute. '''
    def auth(user_name, password):
        if(user_name == "hello" and password == "123456"):
            print("User account correct.")
            print("User account incorrect.")
    def exit():
        print("User exit the system.")
    def welcome():
        print("Welcome to this system. ")
  3. Below is source code. There are two functions in this module run() and run_reflect(). run() function do not use python reflect,  run_reflect() function use python builtin hasattr(), getattr() function to implement python reflect. You can see the code comments for detail explanation.
    # First import commons module from it's package.
    from com.dev2qa.example.reflect import commons
    # This function do not use python reflect. 
    def run():
        # Get user input.
        inp = input("Input command:  ").strip()
        # Split the input string into list.
        args = inp.split(" ")
        # Get the first command.
        cmd = args[0]
        # Run different command use if else to check, this way is not effective when there are so many if else.
        if cmd == "auth":
            user_name = args[1]
            password = args[2]
            commons.auth(user_name, password)
        elif cmd == "exit":
        elif cmd == "welcome":
    # This function use python hasattr(), getattr() function to inplement reflect.
    def run_reflect():
        # Get user input command and arguments.
        inp = input("Input command:  ").strip()
        args = inp.split(" ")
        cmd = args[0]
        # If commons module contains cmd attribute.
        if hasattr(commons,cmd):
            # Get the cmd attribute value from the commons module.
            func = getattr(commons,cmd)
            # Because it is a function, so we can run the function.
            # If user input three argument.
            if(len(args) == 3):
                # Get username and password.
                user_name = args[1]
                password = args[2]
                # Execute the function with input arguments.
                func(user_name, password)
    if __name__ == '__main__':

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.