以下具有多重继承的代码和一个字典类,它给出了这个神秘的错误:
'dict' object is not callable
[但仅第二次我呼叫dump_settings()
,而不是第一次。
'dict'
与什么有关?
from collections import OrderedDict
from abc import ABC, abstractmethod
class Dumpable(ABC):
def __init__(self):
self.dump_settings = None
super().__init__()
def dump_settings(self, settings ):
self.dump_settings = settings
pass
class ItemSet(OrderedDict, Dumpable):
def __init__(self , allow_substitution : bool = False ):
super(OrderedDict, self).__init__()
super(Dumpable, self).__init__()
# also substituting two calls above with the
# following, do not change behavior:
# super().__init__()
self.allow_substitution = allow_substitution
pass
def dump_settings(self,settings):
super().dump_settings(settings)
pass
itemset = ItemSet()
output = open("output.txt", "w", encoding="utf-8")
d= dict( output = output , html = False )
print(repr(d))
# this call seems to have no problems:
itemset.dump_settings(d)
print(repr(d))
# note that the given error "'dict' object is not callable"
# has nothing to do with 'd' param because if you change
# in the followin the 'd' with a non-dictionary object,
# the error remains, for example:
# itemset.dump_settings('hello')
itemset.dump_settings(d)
output.close()
NOTE:该错误与d
变量无关(也就是dictionary
),因为如果使用非字典对象对其进行更改,则该错误仍然存在,例如:
itemset.dump_settings('hello')
我尝试过Python
版本3.5.2 for linux
和3.8.3 for Windows
问题是您用字典替换了dump_settings方法,因此,当您下次再次调用dump_settings时,它现在是一个dict,而不是一个方法,并且像错误提示'dict'不可调用。
记住方法只是类的属性。因此,在创建项目集对象之后。 itemset.dump_settings属性指向该方法。但是,当您调用dump_settings时。然后,您继续执行self.dump_settings = settings(其中settings是您赋予它的dict)。所以现在itemset.dump_settings是一个字典,而不是一个方法。
print(f"itemset.dump_settings, type: {type(itemset.dump_settings)}, {itemset.dump_settings}")
itemset.dump_settings(d)
print(f"itemset.dump_settings, type: {type(itemset.dump_settings)}, {itemset.dump_settings}")
输出
itemset.dump_settings, type: <class 'method'>, <bound method Dumpable.dump_settings of ItemSet()>
itemset.dump_settings, type: <class 'dict'>, {'output': <_io.TextIOWrapper name='output.txt' mode='w' encoding='utf-8'>, 'html': False}
如果要保存字典,则需要在您的类中为其指定一个名称,而该名称尚未是方法的名称。
def dump_settings(self, settings):
self.dump_settings_dict = settings