在Python类字典中更改值时为NoneType

2024-05-23 21:02:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图更改python类的字典,这样每当函数对象被添加到字典中时,我都会添加一个类的实例,在那里我重新定义__call__。 我为元类使用一个自定义字典,在dictionary类的__setitem__中,我实例化了一个用于更改添加函数行为的类,并向字典中添加了一个notnonetype对象。但是,当我用正在包装的函数实例化类并尝试调用相应的函数时,我得到一个“NoneType not callable”错误,我在类字典中包装的函数对象是=None。你知道为什么会这样吗?谢谢!在


Tags: 对象实例函数nonedictionary字典定义错误
2条回答

我不确定您到底做了什么,但您可能会发现setdefault有用:

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

详细信息:Use cases for the 'setdefault' dict method

在我开始之前-张贴的代码是你的真实代码吗?在Python3.2下,它实际上对我不起作用—我已经修复了一点。首先,我改变的是:

class_dict = list()

现在

^{pr2}$

OverloadedFunction.__call__中:

for fkey, function in class_dict.items():
    inspect_t = inspect.getfullargspec(function)
    print(inspect_t)

member_dict.__setitem__中:

if value.__class__.__name__ == "function":
    class_dict[key] = value
    dict.__setitem__(self,key,OverloadedFunction(key,value))

我相信这是你想要的。我从来没有得到NoneType not callable错误-通过这些修改(加上顶部的import inspect),您的代码可以工作并打印参数规范:

$ python3 temp.py
FullArgSpec(args=['self', 'a', 'b'], varargs=None, varkw=None, defaults=None, kwonlyargs=[],    kwonlydefaults=None, annotations={'a': <class '__main__.Asteroid'>, 'b': <class '__main__.Asteroid'>})

现在,您想要实现multimed—我所做的修改排除了这一点,因为您的多方法在每次调用__setitem__时都会被覆盖,所以您可以从那里开始工作(也许可以使用collections.defaultdict(list)和{}到{})。在

我可以提个建议吗?我不认为您需要一个元类-http://www.artima.com/weblogs/viewpost.jsp?thread=101605为python2.x提供了一个非常简单的多方法实现。在

相关问题 更多 >