接受参数并更改类型的 Python 装饰器类
我只是在 python 中玩弄装饰器并享受这种体验,对我来说装饰器类对我来说比装饰器函数更干净,所以我一直在玩这个设计
def returns(object):
"""Enforces return to a specific type"""
def __init__(self, returns):
self.returns = returns
def __call__(self, func):
def wrapped(*args):
out = func(*args)
return self.returns(out)
return wrapped
@returns(int)
def test():
return '4'
上面代码的问题是它返回
------------------------------------------------------------
Traceback (most recent call last):
File "", line 1, in <module>
File "", line 122, in runfile
execfile(filename, glbs)
File "", line 33, in <module>
@returns(int)
TypeError: 'NoneType' object is not callable
我想知道为什么我可以调用 int( )就像一个函数,它有一个可调用的方法,但它在这里说它是 NoneType 并且不可调用。
有什么想法吗?
编辑:请不要再回答问题已经解决,我明白我做错了什么。这是一个错字,我定义的是函数而不是类
Im just playing around with decorators in python and enjoying the experience, to me a decorator class seems cleaner to me than decorator functions so I have been playing with this design
def returns(object):
"""Enforces return to a specific type"""
def __init__(self, returns):
self.returns = returns
def __call__(self, func):
def wrapped(*args):
out = func(*args)
return self.returns(out)
return wrapped
@returns(int)
def test():
return '4'
Problem with the above code is that it returns
------------------------------------------------------------
Traceback (most recent call last):
File "", line 1, in <module>
File "", line 122, in runfile
execfile(filename, glbs)
File "", line 33, in <module>
@returns(int)
TypeError: 'NoneType' object is not callable
Im wondering why I can call int() like a function, and it has a callable method but it says this here as its NoneType and not callable.
Any ideas?
EDIT: Please no more answers the problem has been solved and I understand what I was doing wrong. Its a typo and im defining a function not a class
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
returns()
函数不返回任何内容。你的意思是把它变成一个类吗?Your
returns()
function returns nothing. Did you mean to make it a class?也许你想替换
为
Maybe you want to replace
by