初始化(复杂)静态数据成员的Python方法 [英] Pythonic Way to Initialize (Complex) Static Data Members
问题描述
我有一个包含复杂数据成员的类,我想保持其静态。我想使用函数将其初始化一次。 Pythonic是这样的:
I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this:
def generate_data():
... do some analysis and return complex object e.g. list ...
class Coo:
data_member = generate_data()
... rest of class code ...
函数 generate_data
需要很长时间才能完成,并且返回在a范围内保持不变的数据正在运行的程序。我不希望每次实例化Coo类时都运行它。
The function generate_data
takes a long while to complete and returns data that remains constant in the scope of a running program. I don't want it to run every time class Coo is instantiated.
此外,只要我不为在
__ init __
中,它将保持静态吗?如果Coo中的方法将一些值附加到 data_member
(假设它是一个列表),该添加项将可用于其余实例吗?
Also, to verify, as long as I don't assign anything to data_member
in __init__
, it will remain "static"? What if a method in Coo appends some value to data_member
(assuming it's a list) - will this addition be available to the rest of the instances?
谢谢
推荐答案
在所有方面您都是正确的。 data_member
将创建一次,并且可用于 coo
的所有实例。如果有任何实例对其进行修改,则该修改将对所有其他实例可见。
You're right on all counts. data_member
will be created once, and will be available to all instances of coo
. If any instance modifies it, that modification will be visible to all other instances.
下面是一个示例,展示了所有这些内容,并在最后显示了输出:
Here's an example that demonstrates all this, with its output shown at the end:
def generate_data():
print "Generating"
return [1,2,3]
class coo:
data_member = generate_data()
def modify(self):
self.data_member.append(4)
def display(self):
print self.data_member
x = coo()
y = coo()
y.modify()
x.display()
# Output:
# Generating
# [1, 2, 3, 4]
这篇关于初始化(复杂)静态数据成员的Python方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!