python父类方法的装饰器_Python-在类声明中访问父类装饰器

Let's say I have this class:

class Foo:

@classmethod

def some_decorator(cls, ...):

...

And then I create a subclass which uses the parent class decorator:

class Bar(Foo):

@Foo.some_decorator(...)

def some_function(...)

...

How do I remove the need for Foo. before the decorator name? The below code doesn't work:

class Bar(Foo):

@some_decorator(...)

def some_function(...)

...

I believe this is possible, because the sly library does this.

See their example:

from sly import Lexer, Parser

class CalcLexer(Lexer):

...

@_(r'\d+')

def NUMBER(self, t):

t.value = int(t.value)

return t

...

As you can see, you can type in @_(...) instead of @Lexer._(...).

How do they accomplish this?

解决方案

This is done with a metaclass that implements a __prepare__ method. Excerpt from the docs:

3.3.3.4. Preparing the class namespace

Once the appropriate metaclass has been identified, then the class

namespace is prepared. If the metaclass has a __prepare__ attribute,

it is called as namespace = metaclass.__prepare__(name, bases, **kwds)

(where the additional keyword arguments, if any, come from the class

definition).

To put it in simple terms: You make your __prepare__ method return a dictionary that contains an entry for the decorator. Proof of concept:

class MyMeta(type):

def __prepare__(name, bases):

return {'x': 'foobar'}

class MyClass(metaclass=MyMeta):

print(x) # output: foobar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值