字符串到标识符的绑定在python中是如何工作的?

字符串到标识符的绑定在python中是如何工作的?,python,argparse,Python,Argparse,昨天我在使用python的argparse库,它的一个特性吸引了我的眼球。创建解析器实例后,可以通过将字符串和一些可选值传递给add_argument()向其添加参数。然后,在调用parse_args()之后,返回一个变量,该变量的属性以传递的字符串命名。下面是一个例子: parser = argparse.ArgumentParser() parser.add_argument('layout', help="CSV File containing coordinates and sensor

昨天我在使用python的argparse库,它的一个特性吸引了我的眼球。创建解析器实例后,可以通过将字符串和一些可选值传递给
add_argument()
向其添加参数。然后,在调用
parse_args()
之后,返回一个变量,该变量的属性以传递的字符串命名。下面是一个例子:

parser = argparse.ArgumentParser()
parser.add_argument('layout', help="CSV File containing coordinates and sensor names")
args = parser.parse_args()
layout = csv.reader(open(args.layout)) # now I have the attribute "layout", very cool!
所以,我有点着迷于这个名称绑定,但我不知道它是如何实现的。有人能解释一下这是怎么回事吗?一个例子会很棒。

它是通过函数实现的

基本上

namespace.foo = value
也可以通过以下方式实现:

setattr(namespace,'foo',value)

就这么简单。还有一个获取属性的
getattr
内置程序。

实现这一点的方法很少:

使用
setattr()
动态设置属性值 这就是
argparse
实际上正在做的事情。存储操作如下所示:

class _StoreAction(Action):

    def __init__(self,
                 option_strings,
                 dest,
                 nargs=None,
                 const=None,
                 default=None,
                 type=None,
                 choices=None,
                 required=False,
                 help=None,
                 metavar=None):
        if nargs == 0:
            raise ValueError('nargs for store actions must be > 0; if you '
                             'have nothing to store, actions such as store '
                             'true or store const may be more appropriate')
        if const is not None and nargs != OPTIONAL:
            raise ValueError('nargs must be %r to supply const' % OPTIONAL)
        super(_StoreAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            nargs=nargs,
            const=const,
            default=default,
            type=type,
            choices=choices,
            required=required,
            help=help,
            metavar=metavar)

    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values)
覆盖默认值
\uuuu getattribute\uuuu()
例如,从一些外部提供的字典中获取这些值

class Something(object):
    def __init__(self, values_dict):
        self.values_dict = values_dict
    def __getattribute__(self, name):
        try:
            ## by default trying to access "normal" object's attributes
            return super(Something, self).__getattribute__(name)
        except AttributeError: 
            ## in case that it's not "normal" attribute, taking them from our dict
            value = self.values_dict.get(name)
            if value is None:
                ## it wasn't in the dict, re-raise the AttributeError 
                raise 
            else:
                return value
摆弄
\uuuu dict\uuuu

python“他们是如何做到这一点的?”的一个重要问题是,您可以打开源文件并查看。这是磨练你技能的好方法。
class Something(object):
    def __init__(self, values_dict):
        self.__dict__.update(values_dict)