加入收藏 | 设为首页 | 会员中心 | 我要投稿 财气旺网 - 财气网 (https://www.caiqiwang.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

Python中的 函数分析:参数有冒号,声明后有- 箭头

发布时间:2022-12-06 12:41:37 所属栏目:语言 来源:
导读:  我在查看python的fixture源码时发现 fixture的方法定义形式如下:

  def fixture(

   fixture_function: Optional[_FixtureFunction] = None,

   *,

   scope: "Union[_Scope,
  我在查看python的fixture源码时发现 fixture的方法定义形式如下:
 
  def fixture(
 
      fixture_function: Optional[_FixtureFunction] = None,
 
      *,
 
      scope: "Union[_Scope, Callable[[str, Config], _Scope]]" = "function",
 
      params: Optional[Iterable[object]] = None,
 
      autouse: bool = False,
 
      ids: Optional[
 
          Union[
 
              Iterable[Union[None, str, float, int, bool]],
 
              Callable[[Any], Optional[object]],
 
          ]
 
      ] = None,
 
      name: Optional[str] = None,
 
  ) -> Union[FixtureFunctionMarker, _FixtureFunction]:
 
  我顿时有些凌乱,不知这是什么东东,经过各种网上查找资料,发现这是Python 3.X新增加的一个特性,叫作函数注释 Function Annotations。它的用途虽然不是语法级别的硬性要求,但是顾名思义,它可作为函数额外的注释来用。他的用法也很简单。
 
  在python中定义普通的函数,方法如下:
 
  def f1(a,b):
 
      return a+b
 
  通过函数注释,方法定义如下:
 
  def f2(a: "str类型参数a", b: "str类型参数b") -> str:
 
      print("Annotations:", f2.__annotations__)
 
      return a+b
 
  其中
 
  a: "str类型参数a"代表了对参数a的说明
 
  b: "str类型参数b"代表了对参数b的说明
 
  -> str:代表了函数的返回值
 
  f2.__annotations__查看函数的注释说明
 
  运行 print(f2('aa','bb')),输出:
 
  Annotations: {'a': 'str类型参数a', 'b': 'str类型参数b', 'return': }
 
  aabb
 
  那么定义了函数的参数类型和返回值类型我们是否就不可以对其进行修改了呢,让我们做如下尝试:
 
  print(f2(1,2)),输出:
 
  Annotations: {'a': 'str类型参数a', 'b': 'str类型参数b', 'return': }
 
  可见, Function Annotations它的作用仅仅是为函数进行注释来用,并不能指定参数类型。
 

(编辑:财气旺网 - 财气网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!