我可以在 Python 中的不同类实例之间共享数据吗? [英] Can I share data between different class instances in Python?

查看:44
本文介绍了我可以在 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" ,我理解错误,yz 是不同的实例.我只想知道如何在同一个类的不同实例之间共享数据.

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.

这篇关于我可以在 Python 中的不同类实例之间共享数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆