代码之家  ›  专栏  ›  技术社区  ›  wheaties

如何在2.6的类中定义多参数修饰符

  •  2
  • wheaties  · 技术社区  · 16 年前

    一般不使用Python进行OO编程。这个项目需要它,我遇到了一点麻烦。下面是我用来找出错误所在的代码:

    class trial(object):
        def output( func, x ):
            def ya( self, y ):
                return func( self, x ) + y
            return ya
        def f1( func ):
            return output( func, 1 )
        @f1
        def sum1( self, x ):
            return x
    

    无法编译。我试图添加 @staticmethod 标签的“输出”和“f1”功能,但没有用。通常我会这么做

    def output( func, x ):
        def ya( y ):
            return func( x ) + y
        return ya
    
    def f1( func ):
        return output( func, 1 )
    
    @f1
    def sum1( x ):
        return x
    

    这确实有效。那么我怎样才能在课堂上做到这一点呢?

    3 回复  |  直到 16 年前
        1
  •  5
  •   Will McCutchen    16 年前

    方法装饰器不需要成为类的一部分:

    def output(meth, x):
        def ya(self, y):
            return meth(self, x) + y
        return ya
    
    def f1(meth):
        return output(meth, 1)
    
    class trial(object):
        @f1
        def sum1( self, x ):
            return x
    
    >>> trial().sum1(1)
    2
    

    我倾向于使用 meth 而不是 func

        2
  •  0
  •   estin    16 年前

    试试这个难看的办法

    class trial(object):
    
        def __init__(self):
            #doing this instead of @ statement
            self.sum1 = self.f1(self.sum1)
    
        def output(self, func, x ):
            def ya(y):
                return func(x) + y
            return ya
    
        def f1(self, func):
            return self.output( func, 1 )
    
    
        def sum1(self, x ):
            return x
    
    t = trial()
    
    print t.sum1(5)
    
        3
  •  -2
  •   estin    16 年前

    不可能。 这是个错误的设计。 跟随 The Zen of Python

    您必须首先定义decorator,然后在第二步修饰函数。