【问题标题】:Why TypeError: 'str' object is not callable error has occurred in my code为什么 TypeError: 'str' object is not callable 错误发生在我的代码中
【发布时间】:2019-11-27 12:42:06
【问题描述】:

我是学习 python 的新手,我知道以前有人问过这类问题,但我找不到任何解决方案。请检查我的代码并纠正我关于装饰器的功能,谢谢。

def uppercase(func_one):
    func_one = func_one()
    return func_one.upper()

def split(func_two):
    func_two = func_two()
    return func_two.split()

@split

@uppercase    
def CallFunction():
    return "my string was in lower case"

res = CallFunction()
print(res)

【问题讨论】:

  • 您的代码似乎有什么问题?
  • func_one()func_two()。这些假设传递的变量是可调用的(例如函数或方法)。您正在向这些传递一个字符串,从而引发错误。
  • 还有你为此使用装饰器的原因吗?
  • @Ralf 你检查它以在 python 编译器中运行这段代码,我想我不能在这里解释更多。
  • @RanaAalamgeer 此站点上的用户渴望提供帮助,但我们也希望看到您的努力。阅读How to Ask 并编辑您的问题以包含所有必要的部分,以便我们可以更好地帮助您

标签: python-3.x python-decorators


【解决方案1】:

装饰器令人困惑,可能应该避免使用,直到您对 python 非常熟悉。话虽如此,链接装饰器更加棘手:

from functools import wraps

def split(fn): # fn is the passed in function
    @wraps(fn) # This means we can grabs its args and kwargs
    def wrapped(*args, **kwargs): # This is the new function declaration
        return fn(*args, **kwargs).split()
    return wrapped

def uppercase(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return fn(*args, **kwargs).upper()
    return wrapped

# Order matters. You can't call .upper() on a list
@split
@uppercase 
def CallFunction():
    return "my string was in lower case"

res = CallFunction()
print(res)

或者,如果您不希望这两个装饰器的顺序比您需要处理 list 的情况重要:

def uppercase(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        result = fn(*args, **kwargs)
        if isinstance(result, list):
            return [x.upper() for x in result]
        return result.upper()
    return wrapped

参考:How to make a chain of function decorators?

【讨论】:

    猜你喜欢
    • 2020-12-15
    • 2021-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多