I saw that some students in the comments were asking when the content in this chapter would be used.
# First you have a command.py file with the following content, here we assume there are 100 methods behind it
class MyObject(object): def __init__(self): self.x = 9 def add(self): return self.x + self.x def pow(self): return self.x * self.x def sub(self): return self.x - self.x def div(self): return self.x / self.x
# Then we have an entry file exec.py to perform backend operations based on user input
from command import MyObject computer=MyObject() def run(): inp = input('method>') if inp == 'add': computer.add() elif inp == 'sub': computer.sub() elif inp == 'div': computer.div() elif inp == 'pow': computer.pow() else: print('404')
The if is used to make judgments above, so if there are really 100 methods in my command, then it is impossible for me to write 100 judgments, so here we will use the reflection feature of python, see the following code
from command import MyObject computer=MyObject() def run(x): inp = input('method>') # Check if this property exists if hasattr(computer,inp): # Get it and assign it to a new variable func = getattr(computer,inp) print(func()) else: # without us to set one setattr(computer,inp,lambda x:x+1) func = getattr(computer,inp) print(func(x)) if __name__ == '__main__': run(10)
In fact, much of the content of this chapter involves dynamically loading module classes.