【发布时间】:2011-01-30 14:45:51
【问题描述】:
我想做这样的事情,但到目前为止我还没有取得太大的成功。我想让每个 attr 成为仅在访问时计算 _lazy_eval 的属性:
class Base(object):
def __init__(self):
for attr in self._myattrs:
setattr(self, attr, property(lambda self: self._lazy_eval(attr)))
def _lazy_eval(self, attr):
#Do complex stuff here
return attr
class Child(Base):
_myattrs = ['foo', 'bar']
me = Child()
print me.foo
print me.bar
#desired output:
#"foo"
#"bar"
** 更新 **
这也不起作用:
class Base(object):
def __new__(cls):
for attr in cls._myattrs:
setattr(cls, attr, property(lambda self: self._lazy_eval(attr)))
return object.__new__(cls)
#Actual output (it sets both .foo and .bar equal to "bar"??)
#bar
#bar
** 更新 2 **
使用了__metaclass__ 解决方案,但将其卡在Base.__new__ 中。看起来它需要一个更好定义的闭包——“prop()”——才能正确形成属性:
class Base(object):
def __new__(cls):
def prop(x):
return property(lambda self: self._lazy_eval(x))
for attr in cls._myattrs:
setattr(cls, attr, prop(attr))
return object.__new__(cls)
#Actual output! It works!
#foo
#bar
【问题讨论】:
标签: python