Python中def函数右侧有个->的含义

看看def函数右侧有->和没有的区别

def f(agent:str) -> str:
    print("Annotations:", f.__annotations__)
    return agent

print(f('weixin'))
print(f(1))
# 结果:
# Annotations: {'agent': <class 'str'>, 'return': <class 'str'>}
# weixin
# 1

print(type(f('weixin')))
print(type(f(1)))
# 结果:
# Annotations: {'agent': <class 'str'>, 'return': <class 'str'>}
# string
# int

没有加->的函数

def f(agent:str):
    print("Annotations:", f.__annotations__)
    return agent

print(f('weixin'))
print(f(1))
# 结果:
# Annotations: {'agent': <class 'str'>}
# weixin
# 1

print(type(f('weixin')))
print(type(f(1)))
# 结果:
# Annotations: {'agent': <class 'str'>}
# string
# int

总结:只是单纯说明返回的是什么类型,并没有什么用  

  

  

  

原文地址:https://www.cnblogs.com/lucktomato/p/15264362.html