python父类方法的装饰器_Python – 装饰器 – 试图访问方法的父类

我不认为你可以用装饰器做你想做的事情(快速编辑:使用方法的装饰者,无论如何).构造方法时会调用装饰器,这是在构造类之前.您的代码无法工作的原因是因为调用装饰器时类不存在.

jldupont的评论是要走的路:如果你想设置类的属性,你应该装饰类或使用元类.

编辑:好的,看过你的评论后,我可以想到一个可能适合你的两部分解决方案.使用方法的装饰器设置方法的属性,然后使用元类搜索具有该属性的方法并设置类的相应属性:

def TaggingDecorator(method):

"Decorate the method with an attribute to let the metaclass know it's there."

method.my_attr = 'FOO BAR'

return method # No need for a wrapper, we haven't changed

# what method actually does; your mileage may vary

class TaggingMetaclass(type):

"Metaclass to check for tags from TaggingDecorator and add them to the class."

def __new__(cls, name, bases, dct):

# Check for tagged members

has_tag = False

for member in dct.itervalues():

if hasattr(member, 'my_attr'):

has_tag = True

break

if has_tag:

# Set the class attribute

dct['my_attr'] = 'FOO BAR'

# Now let 'type' actually allocate the class object and go on with life

return type.__new__(cls, name, bases, dct)

而已.使用方法如下:

class Foo(object):

__metaclass__ = TaggingMetaclass

pass

class Baz(Foo):

"It's enough for a base class to have the right metaclass"

@TaggingDecorator

def Bar(self):

pass

>> Baz.my_attr

'FOO BAR'

老实说,但是?使用supported_methods = […]方法.元类很酷,但是那些必须在你之后维护代码的人可能会讨厌你.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值