Is it bad practice to use python's getattr extensively?

后端 未结 2 535
闹比i
闹比i 2021-01-02 09:31

I\'m creating a shell-like environment. My original method of handleing user input was to use a dictionary mapping commands (strings) to methods of various classes, making u

2条回答
  •  时光说笑
    2021-01-02 10:16

    The difference between direct attribute access and using getattr() should be fairly negligible. You can tell the difference between the two versions' bytecodes by using Python's dis module to compare the two approaches:

    >>> import dis
    >>> dis.dis(lambda x: x.foo)
      1           0 LOAD_FAST                0 (x)
                  3 LOAD_ATTR                0 (foo)
                  6 RETURN_VALUE        
    >>> dis.dis(lambda x: getattr(x, 'foo'))
      1           0 LOAD_GLOBAL              0 (getattr)
                  3 LOAD_FAST                0 (x)
                  6 LOAD_CONST               0 ('foo')
                  9 CALL_FUNCTION            2
                 12 RETURN_VALUE  
    

    It does, however, sound like you are developing a shell that is very similar to how the Python library cmd does command line shells. cmd lets you create shells that executes commands by matching the command name to a function defined on a cmd.Cmd object like so:

    import cmd
    
    class EchoCmd(cmd.Cmd):
        """Simple command processor example."""
    
        def do_echo(self, line):
            print line
    
        def do_EOF(self, line):
            return True
    
    if __name__ == '__main__':
        EchoCmd().cmdloop()
    

    You can read more about the module at either the documentation, or at http://www.doughellmann.com/PyMOTW/cmd/index.html

提交回复
热议问题