更改 Python 类字典中的值时 NoneType
我试图更改 python 类的字典,以便每次将函数对象添加到字典中时,我都会添加类的实例,在其中重新定义 __call__
。 我为元类使用自定义字典,并在字典类的 __setitem__
中实例化用于更改所添加函数的行为的类,并向字典添加一个非 NoneType 对象。但是,当我使用我正在包装的函数实例化该类并尝试调用相应的函数时,我收到“NoneType 不可调用”错误,并且我在类字典中包装的函数对象 = None。有什么想法为什么会发生这种情况吗?谢谢!
I'm trying to change the dictionary of a python class so that everytime a function object is added to the dictionary I add an instance of my class where I redefine __call__
instead.
I use a custom dictionary for the metaclass and in __setitem__
of the dictionary class I'm instantiating the class that I use to change the behaviour of the added functions and I add a not NoneType object to the dictionary. However, when I instantiate the class with the functions I'm wrapping and try to call the respective function I get a "NoneType not callable" error and the function object that I've wrapped in the class dictionary is = None. Any ideas why this might happen? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在开始之前 - 发布的代码是您的实际代码吗?它实际上在 Python 3.2 下对我不起作用 - 我已经修复了它。这是我所做的更改,首先:
现在是
在
OverloadedFunction.__call__
中:在
member_dict.__setitem__
中:我相信这就是您的意图。我从未收到
NoneType not callable
错误 - 通过这些修改(加上顶部的importspect
),您的代码可以工作并打印参数规范:现在,您想要实现多重方法 - 我所做的修改排除了这一点,因为您的多重方法在每次调用
__setitem__
时都会被覆盖,因此您可以从那里开始工作(也许使用collections.defaultdict(list)
和将append
改为class_dict[key]
)。我可以建议一下吗?我认为您不需要元类 - http://www.artima.com /weblogs/viewpost.jsp?thread=101605 为 Python 2.x 提供了一个非常简单的多方法实现。
Before I start - is the posted code your actual code? It doesn't actually work for me under Python 3.2 - I've fixed it up a bit. Here's what I've changed, to start:
is now
and in
OverloadedFunction.__call__
:in
member_dict.__setitem__
:I believe this is what you intended. I never got the
NoneType not callable
error - with these modifications (plusimport inspect
at the top), your code works and prints the argument specification:Now, you want to implement the multimethod - the modifications I made preclude that, since your multimethods are overwritten on each call to
__setitem__
, so you can work from there (perhaps usecollections.defaultdict(list)
andappend
toclass_dict[key]
instead).May I suggest something? I don't think you need a metaclass - http://www.artima.com/weblogs/viewpost.jsp?thread=101605 provides a multimethod implementation for Python 2.x that's very simple.
我不确定你到底做了什么,但你可能会发现 setdefault 有用:
详细信息:“setdefault”dict 方法的用例
I am not sure what you have done exactly, but you might find setdefault useful:
Detailed info: Use cases for the 'setdefault' dict method