[英]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
self.connect ['Message'] = The Message TypeError:'instancemethod'对象不支持项目分配
Any ideas please? 有什么想法吗?
You're overwritimg the attribute connect
by the method with the same name. 您会覆盖具有相同名称的方法所
connect
的属性。 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. 如果要使用实例属性,请在
__init__
方法中对其进行定义。
You have defined a method and a variable with the same name connect
. 您已经定义了一个方法和一个具有相同名称
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. 因此,最难的是首先创建名称为connect的字典,然后再使用方法覆盖它。 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) 当您尝试访问字典时,得到的是一个错误,告诉您
connect
方法不支持该操作(这不是字典)
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.