我想通了,我只需要使用__getattr__
来转发对另一个对象的访问,并__iter__
使用新功能进行定义。只要我没有调用任何其他方法来扩展查询,这将与 SQLAlchemy 一起工作,这将创建一个没有这些更改的新对象。我设法通过在计划迭代对象之前包装对象来避免这种情况。
class X:
def __init__(self):
self.prop1 = "prop1"
def __iter__(self):
yield 1
yield 2
yield 3
def method(self):
print "method 1"
class Y:
def __init__(self):
self.prop2 = "prop2"
def __iter__(self):
yield (1,2)
yield (3,4)
yield (5,6)
def another_method(self):
print "method 2"
class FirstInTuple:
def __init__(self, obj):
self.obj = obj
def __getattr__(self, attr):
return getattr(self.obj, attr)
def __iter__(self):
for each in self.obj:
if hasattr(each, '__getitem__'):
yield each[0]
else:
yield each
if __name__ == "__main__":
x = X()
y = Y()
f_x = FirstInTuple(x)
f_y = FirstInTuple(y)
for each in x:
print each
print
for each in y:
print each
print
for each in f_x:
print each
print
for each in f_y:
print each
print
print f_x.prop1
f_x.method()
print
print f_y.prop2
f_y.another_method()
输出:
1
2
3
(1, 2)
(3, 4)
(5, 6)
1
2
3
1
3
5
prop1
method 1
prop2
method 2