Skip to content Skip to sidebar Skip to footer

Can I Share Data Between Different Class Instances In Python?

I have a class option, for which I create an instance z. How can I use the optionbook from instance z in another instance of option, say y? class option(object): nextIdNum = 0

Solution 1:

You already defined a variable, that 'shares data between different instance': nextIdNum, so you can do the same for optionbook.

classoption(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)

Returns:

{'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.

Solution 2:

You need a static variable in the option class, and extend your methods to be able to pass in a variable for which optionbook to use:

classoption(object):
    nextIdNum = 0
    optionbook = {} # this variable is "static", i.e. not bound to an instance, but the class itselfdef__init__(self):
          self.optionbook = {}
          self.options = []
          self.optioncomb = {}

    defaddopttobook(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 += 1defaddoptocomb (self,option, book): # add book-param
         combID = 0if 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 +=1else: 
              raise ValueError('Add options to optionbook first')

    def__str__(self):
        returnstr(self.optionbook)

    defgetOptionbook(self):
        return self.optionbook.copy()

    defgetOptioncomb(self):
        return self.optioncomb.copy()

That way, you can access the static member optionbook via 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)

Post a Comment for "Can I Share Data Between Different Class Instances In Python?"