Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

python 3.x - Why TypeError: 'str' object is not callable error has occurred in my code

I am new to learning python, I know this kind questions asked before but i am not able to find any solutions for it. Please check my code and correct me about decorator's functionality, Thank you.

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Decorators are confusing and probably should be avoided till you are super experienced with python. That being said, chaining decorators is even more tricky:

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)

Alternatively if you don't want the order of these two decorators to matter than you need to handle the list case:

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

Reference: How to make a chain of function decorators?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...