有几种方法可以实现:
用于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)
覆盖默认值__getattribute__()
例如从一些外部提供的字典中获取这些值
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
摆弄着__dict__
class Something(object):
def __init__(self, values_dict):
self.__dict__.update(values_dict)