python类方法调用装饰_Python:装饰一个在继承时要覆盖的类方法

Let's say I have some base class:

class Task:

def run(self):

#override this!

Now, I want others to subclass Task and override the run() method:

class MyTask(Task):

def run(self):

#successful override!

However, the problem is that there is logic that must take place before and after the run() method of every class that subclasses Task.

It seems like one way I could do this would be to define another method in the base class which then calls the run() method. However, I wanted to ask, is there a way to achieve this with decorators? What would be the most pythonic way of doing this?

解决方案

As suggested in the comments, letting the subclasses override a hook instead of run itself would probably be best:

class Task(object):

def run(self):

# before

self.do_run()

# after

class MyTask(Task):

def do_run(self):

...

task = MyTask()

task.run()

However, this is one way you could do it with a class decorator:

def decorate_run(cls):

run = getattr(cls, 'run')

def new_run(self):

print('before')

run(self)

print('after')

setattr(cls, 'run', new_run)

return cls

class Task(object): pass

@decorate_run

class MyTask(Task):

def run(self):

pass

task = MyTask()

task.run()

# prints:

# before

# after

Another way would be to use a metaclass. The advantage of using a metaclass would be that subclasses wouldn't have to be decorated. Task could be made an instance of the metaclass, and then all subclasses of Task would inherit the metaclass automatically.

class MetaTask(type):

def __init__(cls, name, bases, clsdict):

if 'run' in clsdict:

def new_run(self):

print('before')

clsdict['run'](self)

print('after')

setattr(cls, 'run', new_run)

class Task(object, metaclass=MetaTask):

# For Python2: remove metaclass=MetaTask above and uncomment below:

# __metaclass__ = MetaTask

pass

class MyTask(Task):

def run(self):

#successful override!

pass

task = MyTask()

task.run()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值