快速重命名方法 [英] Rename Methods on the Fly

查看:119
本文介绍了快速重命名方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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_Asome_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()

这篇关于快速重命名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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