广泛使用python的getattr是不好的做法吗? [英] Is it bad practice to use python's getattr extensively?

查看:98
本文介绍了广泛使用python的getattr是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个类似shell的环境.我处理用户输入的原始方法是使用字典将命令(字符串)映射到各种类的方法,从而利用了函数是python中的第一类对象的事实.

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 use of the fact that functions are first class objects in python.

出于灵活性的考虑(主要用于解析命令),我正在考虑更改设置,以便使用getattr(command)来获取所需的方法,然后在解析器末尾将参数传递给它.这种方法的另一个优点是,不必每次添加新方法/命令时都更新我的(当前静态实现的)命令字典.

For flexibility's sake (mostly for parsing commands), I'm thinking of changing my setup such that I'm using getattr(command), to grab the method I need and then passing arguments to it at the end of my parser. Another advantage of this approach is not having to update my (currently statically implemented) command dictionary every time I add a new method/command.

我的问题有两个.首先,getattr是否具有与eval相同的问题?第二,我会影响外壳的效率吗?我有多少个方法/命令有关系吗?我目前正在查看30条命令,这些命令最终可能会翻倍.

My question is two fold. First, does getattr have the same problems as eval? Second, will I be taking a hit to the efficiency of my shell? Does it matter how many methods/commands I have? I'm currently looking at 30 some commands, which could eventually double.

推荐答案

直接属性访问与使用getattr()之间的区别应该可以忽略不计.您可以使用Python的dis模块来比较这两种方法,从而分辨出这两个版本的字节码之间的区别:

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  

但是,听起来确实像您在开发一个外壳程序,该外壳程序与Python库cmd的命令行外壳程序非常相似. cmd允许您通过将命令名称与在cmd.Cmd对象上定义的函数进行匹配来创建执行命令的外壳,如下所示:

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()

您可以在文档中或在 http://上阅读有关该模块的更多信息. www.doughellmann.com/PyMOTW/cmd/index.html

这篇关于广泛使用python的getattr是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆