In Python, decorate two methods with the same name to distinguish them

风流意气都作罢 提交于 2019-12-06 06:08:48

You should use a namespace to distinguish the different fs.

Heed the advice of the "Zen of Python":

Namespaces are one honking great idea -- let's do more of those!

Yes, you could, but only with an ugly hack, and only by storing the function with a new name.

You'd have to use the sys._getframe() function to retrieve the local namespace of the calling frame. That local namespace is the class-in-construction, and adding items to that namespace means they'll end up in the class dictionary passed to your metaclass.

The following retrieves that namespace:

callframe = sys._getframe(1)
namespace = callframe.f_locals

namespace is a dict-like object, just like locals(). You can now store something in that namespace (like __function_definitions__ or similar) to add extra references to the functions.

You might be thinking java - methods overloading and arguments signature - but this is python and you cannot do this. The second f() will override the first f() and you end up with only one f(). The namespace is a dictionary and you cannot have duplicated keys.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!