【发布时间】:2014-08-23 17:28:14
【问题描述】:
我有一个类的字段是另一个类的实例。
class Field:
def get(self):
def set(self, value):
def delete(self):
class Document:
def __init__(self):
self.y = Field()
self.z = True
我希望能够做的是,当父实例引用其属性时,它会调用子实例的方法。
d = Document()
d.y = 'some value' # Calls the `set` function of the Field
d.y == 'some value' # Calls the `get` function of the Field
del d.y # Calls the `delete` function of the Field
另一个问题是,当字段类型为 Field 时,我只需要这种行为。
我遇到了递归问题,尝试使用__getattr__ 等,类似于:
def __getattr__(self, key):
if isinstance(getattr(self, key), Field):
return getattr(self, key).get()
return getattr(self, key)
递归很明显为什么会发生......但我该如何避免呢?
我已经在 StackOverflow 上看到了一些示例,但我似乎无法弄清楚如何绕过它。
【问题讨论】:
-
为什么不直接使用描述符?此功能是内置的。
-
谢谢!我会试试看,看看效果如何。
-
附注 idf 你不喜欢使用 Python 3.x,总是让你的类继承自“object”
标签: python python-2.7 recursion getattr