Python 装饰子类的所有方法,并提供重写的手段

发布于 2024-12-17 22:16:03 字数 1665 浏览 3 评论 0原文

我正在努力寻找一种减少样板装饰器的方法。我们有很多使用 @decorate 的类。例如:

class MyClass(Base):
     @decorate
     def fun1(self):
         pass
     @decorate
     def fun2(self):
         pass
     def fun3(self):
         pass

我想让它默认装饰器就在那里,除非有人另外指定。


我使用此代码进行自动包装

from functools import wraps

def myDecorator(func):
    @wraps(func)
    def decorator(self, *args, **kwargs):
        try:
            print 'enter'
            ret = func(self, *args, **kwargs)
            print 'leave'
        except:
            print 'exception'
            ret = None

        return ret

    return decorator

class TestDecorateAllMeta(type):
    def __new__(cls, name, bases, local):
        for attr in local:
            value = local[attr]
            if callable(value):
                local[attr] = myDecorator(value)
        return type.__new__(cls, name, bases, local)

class TestClass(object):
    __metaclass__ = TestDecorateAllMeta

    def test_print2(self, val):
        print val

    def test_print(self, val):
        print val

c = TestClass()
c.test_print1("print 1")
c.test_print2("print 2")

我的问题是:

  1. 是否有更好的方法来完成自动装饰?
  2. 我怎样才能覆盖?

理想情况下,我的最终解决方案类似于:

class TestClass(object):
    __metaclass__ = TestDecorateAllMeta

    def autowrap(self):
        print("Auto wrap")

    @dont_decorate
    def test_dont_decorate(self, val):
        print val

编辑

要对下面的评论之一进行讨论,因为类是可调用的而不是执行

if callable(value):

它应该读取:

if isinstance(value,types.FunctionType) 

I am working on finding a way to reduce boilerplate decorators. We have a lot of classes that use a @decorate. For example:

class MyClass(Base):
     @decorate
     def fun1(self):
         pass
     @decorate
     def fun2(self):
         pass
     def fun3(self):
         pass

I want to make it so by default the decorator is there, unless someone specifies otherwise.


I use this code to do the autowrap

from functools import wraps

def myDecorator(func):
    @wraps(func)
    def decorator(self, *args, **kwargs):
        try:
            print 'enter'
            ret = func(self, *args, **kwargs)
            print 'leave'
        except:
            print 'exception'
            ret = None

        return ret

    return decorator

class TestDecorateAllMeta(type):
    def __new__(cls, name, bases, local):
        for attr in local:
            value = local[attr]
            if callable(value):
                local[attr] = myDecorator(value)
        return type.__new__(cls, name, bases, local)

class TestClass(object):
    __metaclass__ = TestDecorateAllMeta

    def test_print2(self, val):
        print val

    def test_print(self, val):
        print val

c = TestClass()
c.test_print1("print 1")
c.test_print2("print 2")

My question are:

  1. Is there a better way to accompish auto-decorating?
  2. How can I go about overriding?

Ideally my end solution would be something like:

class TestClass(object):
    __metaclass__ = TestDecorateAllMeta

    def autowrap(self):
        print("Auto wrap")

    @dont_decorate
    def test_dont_decorate(self, val):
        print val

Edit

To speak to one of the comments below, since classess are callable instead of doing

if callable(value):

It should read:

if isinstance(value,types.FunctionType) 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鸢与 2024-12-24 22:16:03

我不会让我的类的用户指定 __metaclass__ 属性,而是让它们从定义它的基类派生。无需不必要地暴露管道。

除此之外,看起来还不错。您的 @dont_decorate 函数装饰器可以通过在原始函数上设置一个属性来实现,然后您的类装饰器会检测该属性并跳过装饰(如果存在)。

def dont_decorate(func):
    func._dont_decorate = True
    return func

然后在你的元类中,现在有行 if callable(value): 只需放置:

if callable(value) and not hasttr(value, "_dont_decorate"):

顺便说一句,类是可调用的,所以如果你不想要内部类装饰后,您可能应该使用 isinstance() 而不是 callable() 检查函数。

如果您对更明确的替代方案感兴趣,您可以查看 这个最近的问题,有人想使用类装饰器做本质上相同的事情。不幸的是,这有点复杂,因为这些方法在装饰器看到它们时已经被包装了。

Rather than making the user of my class specify a __metaclass__ attribute I would just have them derive from my base class that defines it. No need to expose the plumbing unnecessarily.

Other than that, looks good, though. Your @dont_decorate function decorator can be implemented by setting an attribute on the original function, which your class decorator then detects and skips the decoration if it is present.

def dont_decorate(func):
    func._dont_decorate = True
    return func

Then in your metaclass, where you now have the line if callable(value): just put:

if callable(value) and not hasttr(value, "_dont_decorate"):

As an aside, classes are callable so if you don't want inner classes decorated, you should probably check for functions using isinstance() rather than callable().

If you are interested in more explicit alternatives, you might take a look at this recent question where someone wanted to do essentially the same thing using a class decorator. Unfortunately, this is a good bit more complicated because the methods are already wrapped by the time the decorator sees them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文