Mike F
Mike F

Reputation: 139

Unable to Create Two Distinct Instances of a Class

I'm encountering a strange issue. I have a file, history.py with the following code:

from speech_controls.nav_object import NavObject

    """Sets up the chat and text history buffers."""

    chat_history = NavObject()
    text_history = NavObject()

In other modules, I import history, and do something such as:

history.chat_history.AddItem(some_str)

For some reason Python appears to be creating one object rather than two, as the above code should imply. That is, text_history and chat_history point to the same object. Does anyone have any idea why this might be occurring? Also, if there is a more Pythonic way to do this I'd definitely like to know.

Upvotes: 0

Views: 89

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798706

Stop using class attributes. Initialize your attributes in the initializer.

Wrong:

class Foo(object):
  bar = []
  baz = {}

Right:

class Foo(object):
  def __init__(self):
    self.bar = []
    self.baz = {}

Upvotes: 3

Related Questions