在Python中,装饰两个具有相同名称的方法以区分它们 [英] In Python, decorate two methods with the same name to distinguish them

查看:93
本文介绍了在Python中,装饰两个具有相同名称的方法以区分它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个框架,供熟悉python的人使用.我已经确定了一些语法,对我和他们来说都可以使用这样的语法,其中Base是实现框架的Base类.

I am writing a framework to be used by people who know some python. I have settled on some syntax, and it makes sense to me and them to use something like this, where Base is the Base class that implements the framework.

class A(Base):
    @decorator1
    @decorator2
    @decorator3
    def f(self):
        pass

    @decorator4
    def f(self):
        pass

    @decorator5
    def g(self)
        pass

我所有的框架都是通过Base的元类实现的.这种设置适用于我的用例,因为所有这些用户定义的类都具有丰富的继承图.我希望用户实现某些方法,或者仅将其保留为pass.用户在此处提供的许多信息都在装饰器中.这样一来,我就可以避免其他解决方案,这些解决方案要求用户进行猴子补丁,提供结构化的字典等类似的内容.

All my framework is implemented via Base's metaclass. This set up is appropriate for my use case because all these user-defined classes have a rich inheritance graph. I expect the user to implement some of the methods, or just leave it with pass. Much of the information that the user is giving here is in the decorators. This allows me to avoid other solutions where the user would have to monkey-patch, give less structured dictionaries, and things like that.

我的问题是f由用户定义了两次(有充分的理由),这应该由我的框架处理.不幸的是,当它到达元类的__new__方法时,属性字典仅包含一个键f.我的想法是使用另一个装饰器,例如@duplicate供用户指示这正在发生,并且两个f的包装方式不同,因此不会相互覆盖.这样的东西可以工作吗?

My problem here is that f is defined twice by the user (with good reason), and this should be handled by my framework. Unfortunately, by the time this gets to the metaclass'__new__ method, the dictionary of attributes contains only one key f. My idea was to use yet another decorator, such as @duplicate for the user to signal this is happening, and the two f's to be wrapped differently so they don't overwrite each other. Can something like this work?

推荐答案

是的,您可以,但是只能使用难看的骇客,并且只能通过使用 new 名称存储该函数.

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

您必须使用 sys._getframe()函数检索调用框架的本地名称空间.该本地名称空间是在建类,将项目添加到该名称空间意味着它们将最终进入传递给您的元类的类字典中.

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是类似dict的对象,就像locals()一样.现在,您可以在该名称空间中存储某物(例如__function_definitions__或类似名称),以添加对函数的额外引用.

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.

这篇关于在Python中,装饰两个具有相同名称的方法以区分它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆