我可以在类中设置类变量吗?

考虑以下简单的类:


class ExampleClass():


    def __init__(self, foo):

        self.foo = foo


    def calc_bar(self):

        baz = self.get_baz()

        return baz * self.foo


    @staticmethod

    def get_baz():

        return <result of unchanging database query>

然后我将它与以下内容一起使用:


from module1 import ExampleClass


foo = 10

myobj = ExampleClass(foo)

bar = myobj.calc_bar()

每次我调用该calc_bar方法时都会查询当前构建数据库的方式。


如何将get_baz方法的输出转换为只为该类设置一次的类属性?


我可以通过以下方式手动完成:


class ExampleClass():


    baz = None


    def __init__(self, foo):

        self.foo = foo


    def calc_bar(self):

        return self.baz * self.foo


---


from module1 import ExampleClass


ExampleClass.foo = <result of unchanging database query>

foo = 10

myobj = ExampleClass(foo)

bar = myobj.calc_bar()

有没有一种方法可以在班级内自动完成?


RISEBY
浏览 127回答 3
3回答

慕标琳琳

get_baz您可以简单地缓存第一次调用时的值。class ExampleClass:&nbsp; &nbsp; _baz = None&nbsp; &nbsp; def __init__(self, foo):&nbsp; &nbsp; &nbsp; &nbsp; self.foo = foo&nbsp; &nbsp; def calc_bar(self):&nbsp; &nbsp; &nbsp; &nbsp; baz = self.get_baz()&nbsp; &nbsp; &nbsp; &nbsp; return baz * self.foo&nbsp; &nbsp; @classmethod&nbsp; &nbsp; def get_baz(cls):&nbsp; &nbsp; &nbsp; &nbsp; if cls._baz is None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cls._baz = <result of query>&nbsp; &nbsp; &nbsp; &nbsp; return cls._baz

肥皂起泡泡

get_baz您可以简单地缓存第一次调用时的值。class ExampleClass:&nbsp; &nbsp; _baz = None&nbsp; &nbsp; def __init__(self, foo):&nbsp; &nbsp; &nbsp; &nbsp; self.foo = foo&nbsp; &nbsp; def calc_bar(self):&nbsp; &nbsp; &nbsp; &nbsp; baz = self.get_baz()&nbsp; &nbsp; &nbsp; &nbsp; return baz * self.foo&nbsp; &nbsp; @classmethod&nbsp; &nbsp; def get_baz(cls):&nbsp; &nbsp; &nbsp; &nbsp; if cls._baz is None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cls._baz = <result of query>&nbsp; &nbsp; &nbsp; &nbsp; return cls._baz

慕无忌1623718

一种选择是将其定义baz为None,然后仅在其为 时才进行get_baz()更新。bazNoneclass ExampleClass:&nbsp; &nbsp; baz = None&nbsp; &nbsp; def calc_bar(self):&nbsp; &nbsp; &nbsp; &nbsp; return self.get_baz() * 2&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; @classmethod&nbsp; &nbsp; def get_baz(cls):&nbsp; &nbsp; &nbsp; &nbsp; if cls.baz is None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;cls.baz = 'hello' # <result of query>&nbsp; &nbsp; &nbsp; &nbsp; return cls.bazec = ExampleClass()print(ec.baz)# Output: Noneprint(ec.calc_bar())# Output: hellohelloprint(ec.baz)# Output: hello
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python