【发布时间】:2011-05-21 18:41:38
【问题描述】:
是否可以在描述符的__init__ 函数期间访问描述符内的“所有者”类,而无需像本例中那样手动传递它?
class FooDescriptor(object):
def __init__(self, owner):
#do things to owner here
setattr(owner, 'bar_attribute', 'bar_value')
class BarClass(object):
foo_attribute = FooDescriptor(owner=BarClass)
【问题讨论】:
-
为什么是
setattr(owner, 'bar_attribute', 'bar_value')而不是owner.bar_attribute = 'bar_value'? -
我很确定 No (没有调用堆栈魔术,我希望在响应中看到)。像这样调用/创建
FooDecoractor并没有什么特别之处。 Pythonic 方式通常是“显式”。 -
有关调用堆栈魔法,请参阅SO: How to get the callers method name?
-
仔细检查后,我什至无法将拥有的类作为参考传递,因为那时它还没有定义。我将不得不找到另一个解决方案。谢谢大家。
标签: python python-2.5