【发布时间】: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