问题 Adding an attribute to a python dictionary from the standard library显示如何将属性添加到内置数据类型。但是有没有一种方法可以一步将属性添加到变量中,以便可以在函数调用中使用它,等同于以下内容:
>>> class Adict(dict):
pass
>>> def myfunc(x):
print(x, x.my_attr)
>>> v = {'a':'cat'}
>>> var = Adict(v)
>>> var.my_attr = 'whatever'
>>> myfunc(var)
{'a': 'cat'} whatever
我想将最后 3 行缩减为一行,例如:
>>> myfunc(Adict(v, my_attr='whatever'))
它传递一个包含两个项目('a' 和 'my_attr')但没有属性的字典,或者
>>> myfunc(Adict(v).my_attr='whatever')
它被解析为关键字参数而不是属性设置。有没有一种方法可以一步设置一个值和一个属性?
-------- 编辑------------
为了回答 Sven 的问题,我正在努力扩展优秀的 genson JSON schema处理器,包含以下代码:
# parse properties and add them individually
for prop, val in schema.items():
if prop == 'type':
self._add_type(val)
elif prop == 'required':
self._add_required(val)
elif prop in ['properties', 'patternProperties']:
v = Adict(val)
v._ptype = prop
self._add_properties(v, 'add_schema')
elif prop == 'items':
self._add_items(val, 'add_schema')
elif prop not in self._other:
self._other[prop] = val
我不需要自定义 dict 的任何特殊功能,除了能够用属性标记它之外,能够清理 properties< 下我丑陋的 3 行代码会很好 以便它在视觉上与其他情况匹配 :-)。我可能会做的是将该标记单独传递给 self._add_properties() 函数。
请您参考如下方法:
您可以引入所谓的构建器(或类工厂模式),它获取所有必要的参数并返回结果对象。这是你想要的吗?
class Adict(dict):
pass
def myfunc(x):
print(x, x.my_attr)
def my_builder(v, **kvargs):
obj = Adict(v)
obj.__dict__.update(kvargs) # internal dictionary with attributes
return obj # return the created object
# Your original code.
v = {'a':'cat'}
var = Adict(v)
var.my_attr = 'whatever'
myfunc(var)
print('------------')
v2 = {'d': 'dog'}
myfunc(my_builder(v2, my_attr='whatever_dog'))
print('------------')
myfunc(my_builder({'c': 'crocodile'}, my_attr='whatever_croc'))
这是一种相当直接的方法,可以完全按照您在三行中所做的操作进行操作。但是, builder 以后可能会聪明得多。它可以测试参数的值和类型,并根据情况创建、初始化和返回其他类型的对象作为结果。这就是类工厂 模式的设计目的——为您完成工作的代理。 (这里的问题是您在执行 myfunc() 后将 obj 扔掉,但您可能打算对该对象做其他事情 - 将它传递到某处或随便。)
