我想创建一个多态结构,它可以用最少的输入工作动态创建,并且非常可读。例如:
a.b = 1
a.c.d = 2
a.c.e = 3
a.f.g.a.b.c.d = cucu
a.aaa = bau
我不想创建中间容器,例如:
^{pr2}$我的问题与此类似:
What is the best way to implement nested dictionaries?
但我对那里的解决方案不满意,因为我认为有一个bug:
即使您不想创建项:假设您想要比较两个多态性结构:它将在第二个结构中创建第一个结构中存在的任何属性,并且只在另一个结构中签入。e、 g组:
a = {1:2, 3: 4}
b = {5:6}
# now compare them:
if b[1] == a[1]
# whoops, we just created b[1] = {} !
我也想得到最简单的符号
a.b.c.d = 1
# neat
a[b][c][d] = 1
# yuck
我确实试图从对象类派生。。。但我无法避免留下与上面相同的错误,即仅仅通过读取属性就可以生成属性:一个简单的dir()将尝试创建诸如“方法”之类的属性。。。就像在这个例子中,它显然被破坏了:
class KeyList(object):
def __setattr__(self, name, value):
print "__setattr__ Name:", name, "value:", value
object.__setattr__(self, name, value)
def __getattribute__(self, name):
print "__getattribute__ called for:", name
return object.__getattribute__(self, name)
def __getattr__(self, name):
print "__getattr__ Name:", name
try:
ret = object.__getattribute__(self, name)
except AttributeError:
print "__getattr__ not found, creating..."
object.__setattr__(self, name, KeyList())
ret = object.__getattribute__(self, name)
return ret
>>> cucu = KeyList()
>>> dir(cucu)
__getattribute__ called for: __dict__
__getattribute__ called for: __members__
__getattr__ Name: __members__
__getattr__ not found, creating...
__getattribute__ called for: __methods__
__getattr__ Name: __methods__
__getattr__ not found, creating...
__getattribute__ called for: __class__
谢谢,真的!在
注:到目前为止,我找到的最好的解决方案是:
class KeyList(dict):
def keylset(self, path, value):
attr = self
path_elements = path.split('.')
for i in path_elements[:-1]:
try:
attr = attr[i]
except KeyError:
attr[i] = KeyList()
attr = attr[i]
attr[path_elements[-1]] = value
# test
>>> a = KeyList()
>>> a.keylset("a.b.d.e", "ferfr")
>>> a.keylset("a.b.d", {})
>>> a
{'a': {'b': {'d': {}}}}
# shallow copy
>>> b = copy.copy(a)
>>> b
{'a': {'b': {'d': {}}}}
>>> b.keylset("a.b.d", 3)
>>> b
{'a': {'b': {'d': 3}}}
>>> a
{'a': {'b': {'d': 3}}}
# complete copy
>>> a.keylset("a.b.d", 2)
>>> a
{'a': {'b': {'d': 2}}}
>>> b
{'a': {'b': {'d': 2}}}
>>> b = copy.deepcopy(a)
>>> b.keylset("a.b.d", 4)
>>> b
{'a': {'b': {'d': 4}}}
>>> a
{'a': {'b': {'d': 2}}}
如果你正在寻找的东西不像你原来的帖子那样动态,但更像你目前为止最好的解决方案,你可能会看到伊恩·比金的formencodevariabledecode能满足你的需求。该包本身是用于web表单和验证的目的,但其中一些方法似乎与您所寻找的非常接近。
如果没有其他东西,它可以作为您自己实现的一个例子。在
一个小例子:
我认为您至少需要检查一下
__getattr__
,确保请求的attrib不是以__
开头和结尾的。与该描述匹配的属性实现了已建立的Python api,因此不应实例化这些属性。即使如此,您最终还是会实现一些API属性,例如next
。在这种情况下,如果将对象传递给某个函数,该函数使用duck类型来确定它是否是迭代器,则会引发异常。在创建一个有效属性名的“白名单”会更好,可以是一个文本集,也可以是一个简单的公式:例如,
name.isalpha() and len(name) == 1
可以用于示例中使用的一个字母attrib。对于更实际的实现,您可能需要定义一组与代码所处的域相适应的名称集。在我想另一种选择是确保您没有动态地创建属于某个协议一部分的各种属性名,因为} module 中abc的方法包含一个部分列表,但我不知道在哪里可以找到完整的列表。在
next
是迭代协议的一部分。^{您还需要跟踪该对象是否创建了任何此类子节点,这样您就知道如何与其他此类对象进行比较。在
如果希望比较避免自生,则必须在检查被比较对象的
__cmp__
方法或rich comparison methods方法。在我有一种潜移默化的感觉,有一些我没有想到的复杂情况,这并不奇怪,因为这并不是Python应该如何工作的。仔细考虑一下,考虑一下这种方法增加的复杂性是否值得。在
相关问题 更多 >
编程相关推荐