Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python开发_function annotations

python开发_function annotations

作者头像
Hongten
发布于 2018-09-13 05:49:51
发布于 2018-09-13 05:49:51
45300
代码可运行
举报
文章被收录于专栏:HongtenHongten
运行总次数:0
代码可运行

在看pythonAPI的时候,发现了一个有趣的东东,即:python的方法(函数)注解(Function Annotation)

原文:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Function annotations are completely optional, arbitrary metadata information about user-defined functions. Neither Python itself nor the standard library use function annotations in any way; this section just shows the syntax. Third-party projects are free to use function annotations for documentation, type checking, and other uses.

Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function. Parameter annotations are defined by a colon after the parameter name, followed by an expression evaluating to the value of the annotation. Return annotations are defined by a literal ->, followed by an expression, between the parameter list and the colon denoting the end of the def statement. The following example has a positional argument, a keyword argument, and the return value annotated with nonsense:
>>> def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...
>>> f('wonderful')
Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': 42}
Arguments: wonderful spam

初略的看了一下,没有理解其参数的涵义,就照着写了一遍程序:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1 def f(ham: 42, eggs: int = 'spam') -> 'Nothing to see here':
2     print('Annotations:', f.__annotations__)
3     print('Arguments:', ham, eggs)
4 
5 f('wonderful')

运行效果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Annotations: {'eggs': <class 'int'>, 'ham': 42, 'return': 'Nothing to see here'}
Arguments: wonderful spam
>>> 

运行效果和python的API中描述的一样。

搜索了一些资料发现了参数的涵义:

我们先来看看几个demo:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
ONE : 这里给ham赋一个初始值'Hongten'
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1 #这里给ham赋一个初始值'Hongten'
2 def f(ham: 42 = 'Hongten', eggs: int = 'spam') -> 'Nothing to see here':
3     print('Annotations:', f.__annotations__)
4     print('Arguments:', ham, eggs)
5 
6 f()

运行效果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Annotations: {'eggs': <class 'int'>, 'ham': 42, 'return': 'Nothing to see here'}
Arguments: Hongten spam
>>> 
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//TWO :  这里把42变为:'这里是ham的注释'
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1 #这里把42变为:'这里是ham的注释'
2 def f(ham: '这里是ham的注释' = 'Hongten', eggs: int = 'spam') -> 'Nothing to see here':
3     print('Annotations:', f.__annotations__)
4     print('Arguments:', ham, eggs)
5 
6 f()

运行效果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Annotations: {'eggs': <class 'int'>, 'return': 'Nothing to see here', 'ham': '这里是ham的注释'}
Arguments: Hongten spam
>>> 
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//THREE :  这里把int变为str
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
1 #这里把int变为str
2 def f(ham: '这里是ham的注释' = 'Hongten', eggs: str = 'spam') -> 'Nothing to see here':
3     print('Annotations:', f.__annotations__)
4     print('Arguments:', ham, eggs)
5 
6 f()

运行效果:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Annotations: {'eggs': <class 'str'>, 'ham': '这里是ham的注释', 'return': 'Nothing to see here'}
Arguments: Hongten spam
>>> 
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//FOUR :  看看一段java函数代码
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
  /**
     * 判断一个字符串是否全为字母,此方法比上面的isAllChar方法效率要高,但是需要的是str中包含非字母字符在靠前面
     * 如:"a2bcd",对于这个字符串,到字符"2"的时候就会终止判断
     * 
     * @param str
     *            所需判断的字符串
     * @return str中是否全为字母字符
     */
    public static boolean isAllChars(String str) {
        if (str == null || str.equals("")) {
            return false;
        }
        boolean flag = true;
        for (int i = 0; i < str.length(); i++) {
            if ((str.charAt(i) < 'a' || str.charAt(i) > 'z')
                    && (str.charAt(i) < 'A' || str.charAt(i) > 'Z')) {
                flag = false;
                break;
            }
        }
        return flag;
    }

到这里你大概知道我想说什么了吧!

总结:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
def f(ham: 42, eggs: int = 'spam') -> "Nothing to see here":
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)

#def关键字定义了函数f,在函数f中有两个参数:ham,eggs。
#其中ham没有默认值,而eggs是由默认值的,其默认值为'spam'.
#参数ham的注释部分为:42;参数eggs的注释部分为:int
# "Nothing to see here"是返回值的注释,这个必须用 '->'连接

#看了java代码后,你会有更直观的认识,注释嘛,你可以根据你自己的想法,想怎么写就怎么写,如42,int;不过不好的注释有时候会给别人阅读代码带来很大的麻烦

#如果上面的代码是这样写:
def f(ham: int = 42, eggs: str = 'spam') -> 'Nothing to see here':
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)

#我想很多人阅读代码的时候就很容易理解啦 
#上面只是个人观点,如果不正确的地方,还请大家指正 #同时也希望大家相互学习:hongtenzone@foxmail.com
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2013-07-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
python开发_html_html处理
经过源文件内容和转换后的内容相比较,我想你知道html.escape()方法的作用了吧
Hongten
2022/05/06
5550
python开发_python中字符串string操作
在python中,对于字符串string的操作,我们有必要了解一下,这样在我们的以后的开发中会给我们带来很多方便
Hongten
2018/09/13
4870
Python(day1):Python 3 教程
Python 介绍及安装教程我们在Python 2.X 版本的教程中已有介绍,这里就不再赘述。
江一铭
2022/06/16
1490
python开发_textwrap文本样式
在看python的API的时候,发现python的textwrap在处理字符串样式的时候功能强大
Hongten
2018/09/13
6070
python开发_textwrap文本样式
python开发_python中的list操作
============================================
Hongten
2018/09/13
8570
python开发_shelve_完整版_博主推荐
=====================================================
Hongten
2018/09/13
4910
python开发_python中str.format()
格式化一个字符串的输出结果,我们在很多地方都可以看到,如:c/c++中都有见过 下面看看python中的字符串格式函数str.format(): 1 #使用str.format()函数 2 3 #使用'{}'占位符 4 print('I\'m {},{}'.format('Hongten','Welcome to my space!')) 5 6 print('#' * 40) 7 8 #也可以使用'{0}','{1}'形式的占位符 9 print('{0},I\'m {1},my
Hongten
2018/09/13
6590
python开发_python文件操作
官方API:os-Miscellaneous operating system interfaces
Hongten
2018/09/13
4070
python开发_python中的module
在python中,我们可以把一些功能模块化,就有一点类似于java中,把一些功能相关或者相同的代码放到一起,这样我们需要用的时候,就可以直接调用了
Hongten
2018/09/13
6780
python开发_python中for循环操作
如果你对python中的for循环不是很清楚,请看看这篇文章:”for循环控制语句——菜鸟的Python笔记“
Hongten
2018/09/13
7920
python开发_python中的range()函数
python中的range()函数的功能hen强大,所以我觉得很有必要和大家分享一下
Hongten
2018/09/13
6130
python开发_HTMLParser_html文档解析
=============================================
Hongten
2022/05/06
4260
python3 教程
编程代码便是:“Hello World!”,以下代码使用Python输出“Hello World” :
py3study
2020/01/03
6800
python开发_logging_日志处理
============================================================
Hongten
2018/09/13
4800
python开发_dbm_键值对存储_完整_博主推荐
============================================
Hongten
2018/09/13
6800
python开发_dbm_键值对存储_完整_博主推荐
python开发_python中的Boolean运算和真假值
python中的真假值: Truth Value Testing Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false: 1.None 2.False 3.zero of any numeric type, for examp
Hongten
2018/09/13
1K0
python开发_zlib_完整版_博主推荐
===============================================
Hongten
2018/09/13
5080
python开发_类型转换convert
E | hongtenzone@foxmail.com  B | http://www.cnblogs.com/hongten
Hongten
2018/09/13
1.1K0
python开发_python日期操作
在python中对日期进行操作的库有: 1 import datetime 2 import time 对日期格式化信息,可以参考官方API: time.strftime datetime 下面是我做的demo: 1 #datetime 2 3 import datetime 4 5 #当前日期 6 now = datetime.datetime.now() 7 print(now.strftime('%Y-%m-%d %H:%M:%S')) 8 print(now.strftime('
Hongten
2018/09/13
8890
python开发_tarfile_文档归档压缩|解压缩
如果在你计算机的c:\\test目录下面没有temp目录,系统会自动创建该目录:c:\\test\\temp
Hongten
2018/09/13
5610
python开发_tarfile_文档归档压缩|解压缩
相关推荐
python开发_html_html处理
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验