Android程序猿带你学python第3章--函数和方法
来源:互联网 发布:php条件判断语句 编辑:程序博客网 时间:2024/06/06 01:33
导读
函数function —— A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body.
方法method —— A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self).
在类里的叫做方法
在类外的叫做函数
可以用type()去验证这个说法
函数和方法
定义函数格式
对于Java程序猿,方法或者函数再熟悉不过了,只不过在python里定义的方式有所区别
def 函数名(参数1, 参数2...参数n): statment
注意点:
1.命名规范 和java一样的是,python采用小写字母加下划线分割的命名方式或者驼峰式
2.def关键字 申明定义函数
3.函数括号里加参数
4.括号后面紧跟冒号
5.函数体4个空格的缩进
定义时给默认值
def add_function(x, y=2): z = x + y print(z)add_function(2)
如果不给有默认值的参数传递值,就采用默认值;如果传递,就用新值
可以用global定义全局变量
返回值
def getName(): return "tony"
不定参
def add_function(a, *args): result = a for i in args: result += i print(result)t = add_function(2,3,4,5,6,7,8)print(t)
不定参数以元组的形式存在
传入字典
def foo(**args): print(args)foo(a=2,b=3,c=4,d=5,e=6,f=7,g=8)试试结果
注释
还是之前的例子"""该函数用于打印a的值和不定参数args的值"""def add_function(a, *args): result = a for i in args: result += i print(result)
总结
相对于Java 函数这块没有多大的区别,只不过传参更灵活了,在下一章讲解类的时候,我们能对函数和方法有一个更深入的理解
- Android程序猿带你学python第3章--函数和方法
- Android程序猿带你学python第0章--导读
- Android程序猿带你学python第1章--基本对象类型
- Android程序猿带你学python第2章--逻辑控制
- Android程序猿带你学python第4章--类
- Android程序猿带你学python第5章--输入与输出(I/O)
- Android程序猿带你学python第6章--异常处理
- 【3分钟带你学】null和undefined
- 第3个python程序:数字和数学计算
- range()函数。 笨方法学python. 循环和列表。
- 习题35,分支和函数,笨方法学python
- 笨方法学Python 习题 19: 函数和变量
- 笨方法学Python 习题 35: 分支和函数
- 《笨方法学python》第一天
- 《笨方法学python》的第三天
- 《笨方法学python》第五天
- 【3分钟带你学】 正则表达式
- 【3分钟带你学】Ajax
- tm32f10x_conf.h
- 创建maven工程常见的错误
- 欢迎使用Markdown编辑器写博客
- html学习
- 仿快看漫画页面
- Android程序猿带你学python第3章--函数和方法
- 【证】:那些可作为GC Roots的对象
- IDEA编辑JSP模板
- 有序广播
- 设计模式(4)-Factory工厂模式
- kiwenlau/hadoop-cluster-docker
- 计算机网络---TCP
- 欢迎使用CSDN-markdown编辑器
- 沈阳集训day1