【问题标题】:Different ways to declare internal class variables in Python. Which is the best one?在 Python 中声明内部类变量的不同方法。哪个是最好的?
【发布时间】:2021-10-31 08:57:36
【问题描述】:

以下代码包括声明类使用的静态变量的几种不同方式。它们之间有什么功能上的区别吗?每个人都有什么优点/缺点?有没有更好的方法我不知道?

# 1st way
class ApplePie:

    type = "apple"

    def __init__(self):
        print(f"I'm an {ApplePie.type} pie!")



# 2nd way
class ApplePie:

    @property
    def type(self) -> str:
        return "apple"

    def __init__(self):
        print(f"I'm an {self.type} pie!")


# 3rd way
from functools import cached_property

class ApplePie:

    @cached_property
    def type(self) -> str:
        return "apple"

    def __init__(self):
        print(f"I'm an {self.type} pie!")

你们会使用哪种方法,为什么?

【问题讨论】:

    标签: python-3.x class caching static-variables


    【解决方案1】:

    您的第一个示例不起作用。你可以像这样定义一个静态变量:

    class ApplePie:
    
        type = "apple"
    
        def __init__(self):
            print(f"I'm an {ApplePie.type} pie!")
    

    这是一个类属性(即它在该类的所有实例之间共享),而不是通过self 访问的实例属性,就像在您的第二个示例中一样。这些在一个类的多个实例中可能不同。

    你的第三个例子是

    对于原本实际上不可变的实例的昂贵计算属性很有用。

    official documentation 中所述。

    【讨论】:

    • 谢谢,我忘了我不能在那里使用 self 。我已将代码示例编辑为正确。
    • @TimEstes 我的解释消除了你的困惑,或者你还有什么想知道的吗?
    • 太棒了!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 2011-01-23
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多