简体   繁体   English

使用基类方法作为派生类中的装饰器

[英]Use a base class method as a decorator in derived classes

I have come across a situation where I have a base class and multiple derived classes. 我遇到了一个基类和多个派生类的情况。 In each of the derived classes I am doing an action of extracting common data from input given to method. 在每个派生类中,我都在执行从提供给方法的输入中提取公共数据的操作。 Thus I have written that piece of code in base class as method so that derived classes could use it directly. 因此,我已在基类中将该代码段作为方法编写,以便派生类可以直接使用它。 But I want to call this function from each method where I want to perform this action. 但是我想从要执行此操作的每个方法中调用此函数。 My question is that can I write a decorator for this action? 我的问题是我可以为此动作编写装饰器吗? I want this decorator to be a member of base class. 我希望这个装饰器成为基类的成员。 Is it possible to use base class method as a decorator in derived classes? 是否可以将基类方法用作派生类中的装饰器?

Base class: 基类:

class BaseRequestHandler(object):

    def __init__(self):
        self.request=None
        self.response=None

    def extractheader(self,requestin):
        ##extracts header from incoming request

Derived class: 派生类:

class DerivedRequestHandler1(BaseRequestHandler):

    def __init__(self):
        super(DerivedRequestHandler1, self).__init__()  

    def handlermethod(self,requestin)
        ##extract headed
        ##call internal API with header

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM