【问题标题】:Partial method inheritance/decorator in pythonpython中的部分方法继承/装饰器
【发布时间】:2020-04-07 15:06:47
【问题描述】:

我注意到在我的函数中,我的函数的开头和底部有很多类似的代码行,例如:

    def foo1():
        print('start')
        print('of ')
        print('a code')

        '''
        a lot of other code for the foo1
        '''

        print('end')
        print('of')
        print('the code')

    def foo2():
        print('start')
        print('of ')
        print('a code')

        '''
        a lot of other code for the foo2
        '''

        print('end')
        print('of')
        print('the code')

我可以将相似的部分放在不同的方法中,如下所示:

def foo_init():
    print('start')
    print('of ')
    print('a code')

def foo_end():
    print('end')
    print('of')
    print('the code')


def foo1():
    foo_init()
    '''
    a lot of other code for the foo1
    '''
    foo_end():

def foo2():
    foo_init()
    '''
    a lot of the other for the foo1
    '''
    foo_end():

所以我想知道,是否有更好/更智能的方法,也许是使用类继承或 for 循环?

【问题讨论】:

    标签: python python-3.x python-2.7


    【解决方案1】:

    你可以定义一个decorator

    import functools
    def inspect(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
    
            print('start')
            print('of ')
            print('a code')
    
            value = func(*args, **kwargs)
    
            print('end')
            print('of')
            print('the code')
    
            return value
        return wrapper
    

    然后简单地使用它:

    @inspect
    def my_func ( arg ) :
        # Do something
        print( "my_func is called with arg =" , arg) 
    

    您可以越来越多地了解装饰器: Primer on Python Decorators

    【讨论】:

    • 非常感谢您提供的优雅解决方案。我以前从未使用过装饰器。我为您的回答学到了很多东西。
    • 欢迎您。我还加了一个链接,看看吧。
    【解决方案2】:

    除了装饰器之外,这是一个上下文管理器的用例。定义上下文管理器的方法有多种,但我将展示一种让您也可以将其用作装饰器的方法。

    from contextlib import ContextDecorator
    
    
    class context(ContextDecorator):
        def __enter__(self):
            print('start')
            print('of ')
            print('a code')
    
        def __exit__(self, *exc):
            print('end')
            print('of')
            print('the code')
    

    然后你可以写任何一个

    @context
    def foo1():
        ...
    

    def foo1():
        with context():
            ...
    

    根据您的具体需求,上下文管理器或装饰器可能更合适。

    【讨论】:

    • 很高兴我提出了这个问题。有了你所有的答案,我打开了装饰器和上下文管理器的全新世界;-)
    【解决方案3】:

    也许使用类继承

    在 OO 中,这是“模板方法”模式:

    class Base:
        def run(self, *args, **kw):
            print('start')
            print('of ')
            print('a code')
    
            value = self.method(*args, **kwargs)
    
            print('end')
            print('of')
            print('the code')
    
            return value
    
    
        def method(self, *args, **kw):
            return None
    
    
    class Child(Base):
        def method(self, *args, **kw):
            return 42
    
    
    c = Child()
    c.run()
    

    但我不建议在不需要时使用类和继承。

    【讨论】:

      猜你喜欢
      • 2018-01-16
      • 2019-08-02
      • 2020-06-03
      • 2011-03-01
      • 2011-05-20
      • 2019-11-27
      • 2011-03-23
      • 2014-02-02
      • 2022-01-18
      相关资源
      最近更新 更多