在 Python 中声明内部 class 变量的不同方式。哪个最好?
Different ways to declare internal class variables in Python. Which is the best one?
以下代码包括几种不同的方法来声明 class 使用的静态变量。它们之间有什么功能上的区别吗?每个都有 advantages/disadvantages 吗?还有什么我不知道的更好的方法吗?
# 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!")
你们会使用哪种方法,为什么?
您的第一个示例不起作用。你可以像这样定义一个静态变量:
class ApplePie:
type = "apple"
def __init__(self):
print(f"I'm an {ApplePie.type} pie!")
这是一个 class 属性(即它在这个 class 的所有实例之间共享),而不是通过 [=11] 访问的实例 属性 =],就像你的第二个例子。这些在 class.
的多个实例中可能不同
你的第三个例子是
Useful for expensive computed properties of instances that are otherwise effectively immutable.
以下代码包括几种不同的方法来声明 class 使用的静态变量。它们之间有什么功能上的区别吗?每个都有 advantages/disadvantages 吗?还有什么我不知道的更好的方法吗?
# 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!")
你们会使用哪种方法,为什么?
您的第一个示例不起作用。你可以像这样定义一个静态变量:
class ApplePie:
type = "apple"
def __init__(self):
print(f"I'm an {ApplePie.type} pie!")
这是一个 class 属性(即它在这个 class 的所有实例之间共享),而不是通过 [=11] 访问的实例 属性 =],就像你的第二个例子。这些在 class.
的多个实例中可能不同你的第三个例子是
Useful for expensive computed properties of instances that are otherwise effectively immutable.