python父类方法的装饰器_在Python中从子级访问父类中的装饰器

how does one go about accessing a decorator from a base class in a child?

I assumed (wrongly) that the ffg. would work:

class baseclass(object):

def __init__(self):

print 'hey this is the base'

def _deco(func):

def wrapper(*arg):

res = func(*arg)

print 'I\'m a decorator. This is fabulous, but that colour, so last season sweetiedarling'

return res

return wrapper

@_deco

def basefunc(self):

print 'I\'m a base function'

This class works fine, but then I create a child class inheriting from this:

class otherclass(baseclass):

def __init__(self):

super(otherclass, self).__init__()

print 'other class'

@_deco

def meh(self):

print 'I\'m a function'

This won't even import properly, let alone run. @_deco is undefined. Trying baseclass._deco throws an unbound method _deco() error, which isn't really surprising.

Any idea how to do this, I'd really like to encapsulate the decorator in the class, but I'm not married to the idea and I'd need to call it in the base & the child class.

解决方案class baseclass(object):

def __init__(self):

print 'hey this is the base'

def _deco(func):

def wrapper(*arg):

res = func(*arg)

print 'I\'m a decorator. This is fabulous, but that colour, so last season sweetiedarling'

return res

return wrapper

@_deco

def basefunc(self):

print 'I\'m a base function'

@_deco

def basefunc2(self):

print "I'm another base function"

#no more uses of _deco in this class

_deco = staticmethod(_deco)

# this is the key. it must be executed after all of the uses of _deco in

# the base class. this way _deco is some sort weird internal function that

# can be called from within the class namespace while said namespace is being

# created and a proper static method for subclasses or external callers.

class otherclass(baseclass):

def __init__(self):

super(otherclass, self).__init__()

print 'other class'

@baseclass._deco

def meh(self):

print 'I\'m a function'

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值