我想创建一个多态结构,可以以最少的打字工作量即时创建,并且可读性强。例如:
a.b = 1
a.c.d = 2
a.c.e = 3
a.f.g.a.b.c.d = cucu
a.aaa = bau
我不想创建一个中间容器,例如:
a.c = subobject()
a.c.d = 2
a.c.e = 3
我的问题与此类似:
但是我对那里的解决方案不满意,因为我认为存在一个错误:
即使您不想要,也会创建项目:假设您要比较 2 个多态结构:它将在第二个结构中创建存在于第一个,刚刚签入另一个。例如:
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__
谢谢,真的!
ps:到目前为止我发现的最佳解决方案是:
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}}}