美文网首页
Reflection in Python

Reflection in Python

作者: 山猪打不过家猪 | 来源:发表于2023-02-15 08:39 被阅读0次

1. Application Scenario

  1. dynamic load modules
  2. route for web URL

2. What is the reflection

  1. __import()__
  2. hasattr() : determine whether there is a corresponding method to handle
  3. getattr(): get the property corresponding to strings
  4. setattr(): create a function
def new_process():
    print("I am new process...")

def main():
    ##fromlist means you can find the child function of src
    ##1.import the .py file below src
    function_01 = __import__("src.func_01",fromlist=True)
    ##determine whether the func_01.py is loaded.
    print(function_01)
    ##2.determine whether func_01.py has class FUNC01
    if hasattr(function_01,"FUNC01"):
        print("It has class Funct01")
        ##3.create a instance object of FUNC01,equal to class_func01 = FUNC01()
        ins_01 = getattr(function_01,"FUNC01")
        ##4. whether there is a function named process
        if hasattr(ins_01,"process"):
            ##5. get funtion of process
            func_process = getattr(ins_01,"process")
            func_process(ins_01)
        else:
            print("There are no function named process!")
        ##6.add a function named new_process
        setattr(ins_01,"new_process",new_process)
        ##7. whether the function has already add to the instance
        if hasattr(ins_01,"new_process"):
            print("it's new_process")
            func_new = getattr(ins_01,"new_process")
            func_new()
        delattr(ins_01,"new_process")

    else:
        print("There are no class named FUNC01")    


if __name__ == "__main__":
    main()
class Calculator:
    def add(self):
        print("add...")
    
    def minus(self):
        print("minus...")

    def multiple(self):
        print("multiple...")
    
    def divide(self):
        print("divide...")
    
    def calculate(self,method):
        if hasattr(self,method):
            func = getattr(self,method)
            func()

cal = Calculator()
cal.calculate("add")

相关文章

网友评论

      本文标题:Reflection in Python

      本文链接:https://www.haomeiwen.com/subject/pwuykdtx.html