我有两个类,其中一个非常昂贵,但是可以重用;另一个类在我的应用程序中有很多实例,但是可以重用昂贵类的一个实例。这一点更容易用例子来解释:
class SomeExpensiveToSetUpClass(object):
def __init__(self):
print("Expensive to set up class initialized")
self.whatever = "Hello"
def do_the_thing(self):
print(self.whatever)
class OftenUsedClass(object):
@staticmethod
@property
def expensive_property():
try:
return OftenUsedClass._expensive_property
except AttributeError:
OftenUsedClass._expensive_property = SomeExpensiveToSetUpClass()
return OftenUsedClass._expensive_property
# I know I could hide the static property in an instance property:
@property
def expensive_property2(self):
try:
return OftenUsedClass._expensive_property
except AttributeError:
OftenUsedClass._expensive_property = SomeExpensiveToSetUpClass()
return OftenUsedClass._expensive_property
#
# And then:
#
# ouc = OftenUsedClass()
# ouc.expensive_property2.do_the_thing()
# ouc.expensive_property2.do_the_thing()
# ouc.expensive_property2.do_the_thing()
#
# but that feels misleading
if __name__ == '__main__':
OftenUsedClass.expensive_property.do_the_thing()
OftenUsedClass.expensive_property.do_the_thing()
OftenUsedClass.expensive_property.do_the_thing()
如您所见,我希望在第一次使用属性时使用@staticmethod
和@property
来基本上记住该属性,但是没有骰子——我要取回property
的实例:
我发现了几种用于记忆装饰器的模式,但没有一种模式适用于静态属性。我错过什么了吗?或者我应该使用另一种模式吗?在
编辑:
我过分简化了我的问题:我应该包括SomeExpensiveToSetUpClass
类实现的名称是在配置文件中提供的,因此直到第一次实例化OftenUsedClass
时我才知道它的名称。在
建议的possible duplicate很接近。
classmethod
修饰符的工作原理如该答案所述:但不需要定义类之外的任何内容,因此:
^{pr2}$工作正常。在
相关问题 更多 >
编程相关推荐