我可以在 Python 中的不同类实例之间共享数据吗?
问题描述:
我有一个 option
类,我为其创建了一个实例 z
.
I have a class option
, for which I create an instance z
.
如何在 option
的另一个实例中使用实例 z
中的 optionbook
,例如 y
?
How can I use the optionbook
from instance z
in another instance of option
, say y
?
class option(object):
nextIdNum = 0
def __init__(self):
self.optionbook = {}
self.options = []
self.optioncomb = {}
def addopttobook(self,optiondescription):
self.idNum = option.nextIdNum
if optiondescription in self.optionbook.values() :
raise ValueError('Duplicate Option')
self.optionbook["Opt.ID." + str(self.idNum)] = optiondescription
option.nextIdNum += 1
def addoptocomb (self,option):
combID = 0
if option in self.optionbook.values():
if option in self.options:
raise ValueError('Duplicate Option')
self.combID = combID
self.options.append(str(list(self.optionbook.keys())[list(self.optionbook.values()).index(option)]) +":"+ option)
self.optioncomb["Optcomb.ID." + str(self.combID)] = self.options
self.combID +=1
else:
raise ValueError('Add options to optionbook first')
def __str__(self):
return str(self.optionbook)
def getOptionbook(self):
return self.optionbook.copy()
def getOptioncomb(self):
return self.optioncomb.copy()
z = option()
z.addopttobook('open the well')
y = option()
y.addoptocomb('open the well')
这给了我一个 ValueError "Add options to optionbook first"
,我理解错误,y
和 z
是不同的实例.我只想知道如何在同一个类的不同实例之间共享数据.
This gives me a ValueError "Add options to optionbook first"
, I understand the error, y
and z
are different instances. I just want to know how to share data between different instances of same class.
答
您已经定义了一个在不同实例之间共享数据"的变量:nextIdNum
,因此您可以对 optionbook
.
You already defined a variable, that 'shares data between different instance': nextIdNum
, so you can do the same for optionbook
.
class option(object):
nextIdNum = 0
optionbook = {}
def __init__(self):
self.options = []
self.optioncomb = {}
... # rest of your code here
z = option()
z.addopttobook('z opens the well 1')
z.addopttobook('z opens the well 2')
y = option()
z.addopttobook('y opens the well 1')
y.addoptocomb('z opens the well 1')
print(option.optionbook)
print (option.optionbook == z.optionbook == y.optionbook)
返回:
{'Opt.ID.0': 'z opens the well 1', 'Opt.ID.1': 'z opens the well 2', 'Opt.ID.2': 'y opens the well 1'}
True # >> The class itself as well as all instances share the same data.