通常不要在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
Run Code Online (Sandbox Code Playgroud)
哪个不编译.我试图将@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
Run Code Online (Sandbox Code Playgroud)
哪个确实有效.那么如何在课堂上学习呢?
您的方法装饰器不需要成为类的一部分:
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
Run Code Online (Sandbox Code Playgroud)
我倾向于使用meth而不是func装饰器,我知道我将应用于方法,只是为了试图将它直接放在我自己的头脑中.
| 归档时间: |
|
| 查看次数: |
399 次 |
| 最近记录: |