3 回答
TA贡献1830条经验 获得超9个赞
get_baz您可以简单地缓存第一次调用时的值。
class ExampleClass:
_baz = None
def __init__(self, foo):
self.foo = foo
def calc_bar(self):
baz = self.get_baz()
return baz * self.foo
@classmethod
def get_baz(cls):
if cls._baz is None:
cls._baz = <result of query>
return cls._baz
TA贡献1829条经验 获得超6个赞
get_baz您可以简单地缓存第一次调用时的值。
class ExampleClass:
_baz = None
def __init__(self, foo):
self.foo = foo
def calc_bar(self):
baz = self.get_baz()
return baz * self.foo
@classmethod
def get_baz(cls):
if cls._baz is None:
cls._baz = <result of query>
return cls._baz
TA贡献1744条经验 获得超4个赞
一种选择是将其定义baz为None,然后仅在其为 时才进行get_baz()更新。bazNone
class ExampleClass:
baz = None
def calc_bar(self):
return self.get_baz() * 2
@classmethod
def get_baz(cls):
if cls.baz is None:
cls.baz = 'hello' # <result of query>
return cls.baz
ec = ExampleClass()
print(ec.baz)
# Output: None
print(ec.calc_bar())
# Output: hellohello
print(ec.baz)
# Output: hello
添加回答
举报