开发者

How to define multi-argument decorators within a class in 2.6

开发者 https://www.devze.com 2023-01-03 16:23 出处:网络
Generally don\'t do OO-programming in Python.This project requires it and am running into a bit of trouble.Here\'s my scratch code for attempting to figure out where it went wrong:

Generally don't do OO-programming in Python. This project requires it and am running into a bit of trouble. Here's my scratch code for attempting to figure out where it went wrong:

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

which doesn't compile. I've attempted to add the @staticmethod tag to the "output" and "f1" functions but to no avail. Normally I'd do this

def output( func, x ):
    def ya( y ):
        retur开发者_运维问答n func( x ) + y
    return ya

def f1( func ):
    return output( func, 1 )

@f1
def sum1( x ):
    return x

which does work. So how do I get this going in a class?


There's no need for your method decorators to be a part of the class:

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

I tend to use meth instead of func in decorators I know I'll be applying to methods, just to try to keep it straight in my own head.


Try this ugly solution

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)


No way. This is a wrong design. Follow for The Zen of Python

When you decorate a function calling the decorator by @ it must be already defined.

You must at first - define decorator and at the second step decorate a function.

0

精彩评论

暂无评论...
验证码 换一张
取 消