接受参数并更改类型的 Python 装饰器类

发布于 2024-11-15 07:01:58 字数 895 浏览 1 评论 0原文

我只是在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

内心激荡 2024-11-22 07:01:58

您的 returns() 函数不返回任何内容。你的意思是把它变成一个类吗?

Your returns() function returns nothing. Did you mean to make it a class?

耳钉梦 2024-11-22 07:01:58

也许你想替换

def returns(object):

class returns(object):

Maybe you want to replace

def returns(object):

by

class returns(object):
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文