我需要实现这样的行为:
obj.attr1.attr2.attr3 --> obj.attr1__attr2__attr3
看起来我必须覆盖obj的类__getattribute__
,并以某种方式使用python描述符。
更新
我有一个django项目。
obj是django-haystack的SearchResult实例,它包含来自django模型的大量非规范化数据(user__name
,user__address
),我需要将其作为result.user.name
访问兼容性原因。
更新THC4k的答案:
如果我有:
class Target(object):
attr1 = 1
attr1__attr2__attr3 = 5
>>> proxy.attr1
1
>>> proxy.attr1.attr2.attr3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'attr2'
非常感谢任何帮助。
答案 0 :(得分:3)
我希望您知道自己在做什么,这不仅仅是避免修复现有代码的方案。
我认为有合理的理由这样做,毕竟我已经在Lua中做了类似的事情来实现一些C代码的包装,而不必为每个公开的函数实际编写代码。
但是你应该至少将实际的类与代理分开:
# the proxy maps attribute access to another object
class GetattrProxy(object):
def __init__(self, proxied, prefix=None):
self.proxied = proxied
self.prefix = prefix
def __getattr__(self, key):
attr = (key if self.prefix is None else self.prefix + '__' + key)
try:
# if the proxied object has the attr return it
return getattr(self.proxied, attr)
except AttributeError:
# else just return another proxy
return GetattrProxy(self.proxied, attr)
# the thing you want to wrap
class Target(object):
attr1__attr2__attr3 = 5
t = Target()
proxy = GetattrProxy(t)
print proxy.attr1.attr2.attr3
@katrielalex建议:
class GetattrProxy2(GetattrProxy):
def __getattr__(self, key):
attr = (key if self.prefix is None else self.prefix + '__' + key)
proxy = GetattrProxy2(self.proxied, attr)
# store val only if the proxied object has the attribute,
# this way we still get AttributeErrors on nonexisting items
if hasattr(self.proxied, attr):
proxy.val = getattr(self.proxied, attr)
return proxy
proxy = GetattrProxy2(t)
proxy.attr1.val # 1
proxy.attr1.attr2.attr3.val # 5
proxy.attr1.attr2.val # raise AttributeError
答案 1 :(得分:1)
对于您拥有属性名称列表的情况,您可以使用itertools()
函数(在python-3.x functools.reduce()
中)和getattr()
内置函数:
以下是一个例子:
In [1]: class A:
...: def __init__(self):
...: self.a1 = B()
...:
In [2]: class B:
...: def __init__(self):
...: self.b1 = C()
...:
In [3]: class C:
...: def __init__(self):
...: self.c1 = 7
...:
In [4]: from functools import reduce
In [5]: reduce(getattr, [A(), 'a1', 'b1', 'c1'])
Out[5]: 7
答案 2 :(得分:0)
class A:
def __init__(self, a):
self.a = a
# create objects with many a atributes..
a = A(A(A(A('a'))))
x = a
# as long as a has atribute a continue...
while hasattr(x, 'a'):
print x
x = x.a