我可以在Python中的不同类实例之间共享数据吗?

时间:2017-11-16 15:45:59

标签: python oop static

我有一个班级option,我为此创建了一个实例z

如何在optionbook的另一个实例中使用实例z中的option,说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是不同的实例。我只是想知道如何在同一个类的不同实例之间共享数据。

2 个答案:

答案 0 :(得分:0)

您需要option类中的静态变量,并扩展您的方法,以便能够传入要使用optionbook的变量:

class option(object):
    nextIdNum = 0
    optionbook = {} # this variable is "static", i.e. not bound to an instance, but the class itself

    def __init__(self):
          self.optionbook = {}
          self.options = []
          self.optioncomb = {}

    def addopttobook(self,optiondescription, book): # add book-param
        self.idNum = option.nextIdNum
        if optiondescription in self.optionbook.values() :
            raise ValueError('Duplicate Option')
        book["Opt.ID." + str(self.idNum)] = optiondescription 
        option.nextIdNum += 1

    def addoptocomb (self,option, book): # add book-param
         combID = 0  
         if option in book.values():
               if option in self.options:
                    raise ValueError('Duplicate Option')
               self.combID = combID
               self.options.append(str(list(book.keys())[list(book.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()

这样,您就可以通过optionbook访问静态成员option.optionbook

z = option()
# you can always access the static member by referencing it via the class-name
# it is not bound to any concrete instances
z.addopttobook('open the well', option.optionbook) 
y = option()
y.addoptocomb('open the well', option.optionbook)
print(option.optionbook)

答案 1 :(得分:0)

您已经定义了一个变量,它在不同的实例之间共享数据':nextIdNum,因此您可以对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.