当前位置:   article > 正文

python函数定义

python函数定义

Function definitions函数定义[更新中]

考虑到函数部分为python中的难点和重点,这里主要对函数定义(Function Definitions)结构中的各部分进行展开介绍,主要包括装饰器(Decorator)、内置装饰器(@staticmethod, @classmethod, @property)、函数参数(Paramter_list)、标识符“->”等。该文主要用于记录和总结学习中遇到的问题,如有不正确的表述欢迎指正。
关键字:装饰器;类方法;静态方法;参数列表;

funcdef                 ::=  [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
decorators              ::=  decorator+
decorator               ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
dotted_name             ::=  identifier ("." identifier)*
parameter_list          ::=  defparameter ("," defparameter)* ["," [parameter_list_starargs]]
                             | parameter_list_starargs
parameter_list_starargs ::=  "*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]]
                             | "**" parameter [","]
parameter               ::=  identifier [":" expression]
defparameter            ::=  parameter ["=" expression]
funcname                ::=  identifier
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

注: [ ]里的内容为可选项," "内的符号为关键标识符,不可省略。
官方文档链接

funcdef

[decorators]
def funcname ( [parameter_list] ) ["->" expression] :
    suite
  • 1
  • 2
  • 3

decorator:为装饰器(装饰器的书写规范为:@decorator_name),一个函数可以有多个装饰器,执行顺序是从下到上。funcname:为函数名称。parameter_list:为参数列表。-> expression:用于定义函数返回值类型(很少使用)。

decorators

函数可以被一个或多个装饰器表达式(decorator expressions)包装。装饰器可以是一个方法@deco_name,可以带参数@deco_name(args)也可以是一个类@deco_class_name。python中内置的装饰器有三个@classmethod@staticmethod@properety

应用场景

  • 场景一:因为业务需求需要记
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/616818
推荐阅读
相关标签
  

闽ICP备14008679号