-2

I want to create a variable in Python that is shared by all instances of object.

class myobj:
  shared = []

  def add(item):
     self.shared.append(item)

  def get():
     return self.shared

item = myobj()
item.add("Hello")

item2 = myobj()
item2.add("Dave")

item.get()  # this should return [Hello, Dave]
item2.get() # this also should return [Hello, Dave]
Cory
  • 14,865
  • 24
  • 57
  • 72
  • 2
    -1 What's wrong with what you have? This should work as long as you use new-style classes. – Marcin Jul 19 '12 at 17:04
  • 1
    @cory: What do you mean by "re-read the question"? What information is there that relates to his comment? – David Robinson Jul 19 '12 at 17:07
  • @cory Nowhere do you say what's wrong with the code you have. It does what you ask of it, as long as you fix the errors (which would be errors in all cases, independent of your question): http://ideone.com/hoGaQ – Marcin Jul 19 '12 at 17:07
  • @cory, you're repeating yourself but not answering the questions. Have you tried running the code that you posted? – David Robinson Jul 19 '12 at 17:09

4 Answers4

4

If you fix two errors in your code that are unrelated to your question, your code does exactly what you're asking it to.

The two errors are to change:

def add(item):

to

def add(self, item):

and change

def get():

to

def get(self):

At that point, running your code does get ["Hello", "Dave"] returned from each.

David Robinson
  • 77,383
  • 16
  • 167
  • 187
2

Your code works as you expect once you provide a parameter for self in your methods:

class myobj:
  shared = []

  def add(self, item): # added self parameter
     self.shared.append(item)

  def get(self): # added self parameter
     return self.shared

I suggest reading through the answers for Python 'self' explained.

Community
  • 1
  • 1
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
0

This will work:

class myobj:
  shared = []

  def add(self, item):
     self.shared.append(item)

  def get(self):
     return self.shared

item = myobj()
item.add("Hello")

item2 = myobj()
item.add("Dave")

item.get()  # returns [Hello, Dave]
item2.get() # also returns [Hello, Dave]
ecatmur
  • 152,476
  • 27
  • 293
  • 366
0

Here's proof of the three posters:

>>> class Foo:
...      shared = []
...
...      def add(self, item):
...           self.shared.append(item)
...
...      def get(self):
...           return self.shared
... 
>>> item = Foo()
>>> item.add('hello')
>>> item2 = Foo()
>>> item2.add('world')
>>> item2.get()
['hello', 'world']
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284