快速重命名方法

编程入门 行业动态 更新时间:2024-10-11 15:20:34
本文介绍了快速重命名方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们可以在类定义时使用元类重命名类方法.这个问题不是不是.

We can rename class methods at class definition time with a metaclass. This question is not about that.

这更多是一个思想实验,请给我一点幽默.

This is more of a thought experiment, so humour me a little please.

说我想写两个这样使用的装饰器:

Say I wanted to write two decorators that are used like this:

class SomeClass(object): @append_A def some_method( self ): pass @append_B def some_method( self ): pass

这将导致SomeClass具有两种方法:some_method_A和some_method_B

Which would result in SomeClass having two methods: some_method_A and some_method_B

这有可能吗?如果可以,您能指出我正确的方向吗?

Is this possible and if so, can you point me in the right direction?

我尝试过几种不同的更改框架f_locals的方法,但是方法名称仍然存在.

I've tried changing the frame's f_locals a few different ways, but the method name still persists.

推荐答案

否,如文档:

装饰器语法只是语法糖,以下两个函数定义在语义上是等效的:

The decorator syntax is merely syntactic sugar, the following two function definitions are semantically equivalent:

def f(...): ... f = staticmethod(f) @staticmethod def f(...): ...

在此处.

我想我们可以做一些事情,例如将方法留在装饰器中,还可以在定义的范围内添加一个具有已编辑名称的新方法(本例为类).最主要的是定义两个具有相同名称的方法,然后以传递给元类的两个不同命名的方法结束.

I guess we could do something like leave the method alone in the decorator but also add a new method with an edited name in the scope it was defined (this case the class). The main thing is defining two methods with the same name then ending up with two differently named methods which are passed to the metaclass.

为此,您可以使用类装饰器:

def append_B(func): func.suffix='_B' return func def appendable(class_obj): for name in dir(class_obj): if not name.startswith('_'): attr = class_obj.__dict__[name] #getattr(class_obj, name) suffix = getattr(attr, 'suffix', None) if isinstance(suffix,str): attr.suffix = None setattr(class_obj,name+suffix, getattr(class_obj, name)) #delattr(class_obj,name) return class_obj

以下用法允许您为同一方法定义两个名称:

The following usage allows you to define two names for the same method:

@appendable class B(object): @append_B def some_method(s): print 'B.some_method' b=B() b.some_method() b.some_method_B()

更多推荐

快速重命名方法

本文发布于:2023-11-30 13:49:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650215.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:重命名   快速   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!