简体   繁体   中英

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?

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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM