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 ( commons.py ) and visit ( visit.py ) in reflect package.
  2. Below is the commons.py 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.")
        else:
            print("User account incorrect.")
    
    
    def exit():
        print("User exit the system.")
    
    
    def welcome():
        print("Welcome to this system. ")
  3. Below is visits.py 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":
            commons.exit()
        
        elif cmd == "welcome":
            commons.welcome()
        
        else:
            print("404")
    
    # 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)
            else:    
                func()
        else:
            print("404")
        
    
    if __name__ == '__main__':
        #run()
        run_reflect()

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.