赞
踩
考虑到函数部分为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
注:
[ ]
里的内容为可选项," "
内的符号为关键标识符,不可省略。
官方文档链接
[decorators]
def funcname ( [parameter_list] ) ["->" expression] :
suite
decorator:为装饰器(装饰器的书写规范为:@decorator_name
),一个函数可以有多个装饰器,执行顺序是从下到上。funcname
:为函数名称。parameter_list
:为参数列表。-> expression
:用于定义函数返回值类型(很少使用)。
函数可以被一个或多个装饰器表达式(decorator expressions)包装。装饰器可以是一个方法@deco_name
,可以带参数@deco_name(args)
也可以是一个类@deco_class_name
。python中内置的装饰器有三个@classmethod
,@staticmethod
,@properety
。
场景一
:因为业务需求需要记Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。