在Python中记静态属性

2024-04-25 02:15:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个类,其中一个非常昂贵,但是可以重用;另一个类在我的应用程序中有很多实例,但是可以重用昂贵类的一个实例。这一点更容易用例子来解释:

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的实例:

^{pr2}$

我发现了几种用于记忆装饰器的模式,但没有一种模式适用于静态属性。我错过什么了吗?或者我应该使用另一种模式吗?在

编辑:

我过分简化了我的问题:我应该包括SomeExpensiveToSetUpClass类实现的名称是在配置文件中提供的,因此直到第一次实例化OftenUsedClass时我才知道它的名称。在


Tags: the实例selfreturn属性defpropertydo
1条回答
网友
1楼 · 发布于 2024-04-25 02:15:08

建议的possible duplicate很接近。classmethod修饰符的工作原理如该答案所述:

class classproperty(object):
    def __init__(self, getter):
        self.getter = getter
    def __get__(self, instance, owner):
        return self.getter(owner)

但不需要定义类之外的任何内容,因此:

^{pr2}$

工作正常。在

相关问题 更多 >