Python中的部分方法继承/装饰器

哥德曼

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

    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循环?

阿米尔·赫姆兹

您可以定义一个 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) 

您可以了解有关装饰器的更多信息:Python Decorators入门

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章