【发布时间】:2018-07-18 17:20:38
【问题描述】:
我希望将大量样板代码转换为使用装饰器,但我不知道该怎么做。
我当前的代码如下所示:
import time # for demonstration
class C(object):
def large_function(self, optional_param=[]):
"""Large remote query that takes some time"""
time.sleep(3)
# usually run without optional_param
return ['val'] + optional_param
@property
def shorthand(self):
"""Docstr..."""
if not hasattr(self, "_shorthand"):
setattr(self, "_shorthand", self.large_function())
return self._shorthand
这就像我想要的那样工作,但是写很多这些显然很烦人。一个更短的例子,似乎做同样的事情:
import time # for demonstration
def lazy(self, name, func):
attr_name = "_" + name
if not hasattr(self, attr_name):
setattr(self, attr_name, func())
return getattr(self, attr_name)
class C(object):
def large_function(self, optional_param=[]):
"""Large remote query that takes some time"""
time.sleep(3)
# usually run without optional_param
return ['val'] + optional_param
@property
def shorthand(self):
"""Docstr..."""
return lazy(self, 'shorthand', self.large_function)
但是,这似乎仍然很冗长。最理想的情况是:
class C(object):
@add_lazy_property('shorthand')
def large_function(self, optional_param=[]):
"""Large remote query that takes some time"""
time.sleep(3)
# usually run without optional_param
return ['val'] + optional_param
c = C()
print(c.shorthand)
print(c.large_function(['add_param'])
不幸的是,我发现的惰性装饰器完全掩盖了底层功能。我尝试了几个setattr() 的函数,但很快就变得混乱了。有什么办法可以用一个装饰器'add_lazy_property'来做到这一点?如果我可以添加我自己的文档字符串或至少复制函数的文档字符串,则可以加分。
【问题讨论】:
标签: python properties decorator python-decorators