Phorce
Phorce

Reputation: 4642

Python Accessing Dictionary and changing values - Error

I cannot seem to figure this out, and, It's diving my crazy. Let's assume I have the following class:

class Test:

 connect = {'Message': None}

 def connect(self):
  if not self.connect['Message']:
     print "Message is not set"
  else:
     print "Message is active and set!"

 def connectMSG(self, theMessage):
     self.connect['Message'] = theMessage

The following looks ok. I can't seem to visually see an error however, I get the following:

self.connect['Message'] = theMessage TypeError: 'instancemethod' object does not support item assignment

Any ideas please?

Upvotes: 2

Views: 73

Answers (3)

Developer
Developer

Reputation: 8400

Corrections are:

class Connection:
   def __init__(self):
       self.connect = {'Message': None}              #moved here

   def Check(self):                                  #renamed
       if not self.connect['Message']:
           print "Message is not set."
       else:
           print "Message is active and set!"

   def Connect(self, theMessage):                    #renamed
       self.connect['Message'] = theMessage

cnt = Connection()

Upvotes: 0

jabaldonedo
jabaldonedo

Reputation: 26572

You have defined a method and a variable with the same name connect. So you have overwritten your dictionary with your method, change the name of one of them.

So what is happing is that first you create the dictionary with name connect, but then you override it with a method. When you try to access the dictionary what you are get is an error telling you that connect method does not support that operation (it is not a dict)

Upvotes: 2

Matthias
Matthias

Reputation: 13222

You're overwritimg the attribute connect by the method with the same name. Rename your attribute.

The next question would be, if you really want to have a class attribute or an instance attribute. If you want an instance attribute define it in the __init__ method.

Upvotes: 2

Related Questions