python学习之函数
1、函数名可以被赋值
比如:
def aaa():
pass b = aaa//将函数名字赋值给b b()//跟aaa()效果一样
2、return
2.1、如果函数不写return的话,会默认返回None
2.2、return后,函数下面的语句不会被执行,中断函数操作
2.3、return个什么东西都行,哪怕是个列表.....
3、pycharm使用断点调试的话,需要用debug模式(向右小箭头的小虫子)
4、参数:
默认参数必须写在后边
def aaa(a1, a2 = 1):
pass
//不能将a1搞成默认参数,语法都通不过
指定参数
def aaa(a1, a2):
pass aaa(a2 = 1, a1 = 2)
动态参数
def aaa(*arg)://一个*
print(arg, type(arg)) aaa(1, 2, 3)//输出结果为元祖 (1, 2, 3) <class 'tuple'>
def aaa(**arg)://两个*
print(arg, type(arg)) aaa(a1=11, a2=22, a3=33)//输出结果为字典 {'a1':11, 'a2':22, 'a3':33} <class 'dict'>
将两种参数组合起来,这就碉堡了....
一个*的参数放前面
传参也是一样,指定参数放后面
def aaa(*args, **kwargs):
print(args, type(args))
print(kwargs, type(kwargs)) aaa(1, 2, 3, a1=11, a2=22, a3=33)
//输出结果为元祖
(1, 2, 3) <class 'tuple'>
//输出结果为字典
{'a1':11, 'a2':22, 'a3':33} <class 'dict'>
着重看下下面的东西(更屌。。)
def aaa(*args, **kwargs):
print(args, type(args))
print(kwargs, type(kwargs))
a = [1, 2, 3]
b = {'a1':11, 'a2':22, 'a3':33}
aaa(a, b)
//输出结果为元祖
([1, 2, 3], {'a1':11, 'a2':22, 'a3':33}) <class 'tuple'> aaa(*a, **b)//这里添加了*号后,就可以对应的传参数
//输出结果是我们想要的
(1, 2, 3) <class 'tuple'>
{'a1':11, 'a2':22, 'a3':33} <class 'dict'>
通过动态参数来实现字符串的格式化
//通过列表传参数
a = "{0} is {1}"
b = ['haha', 'sb']
ret = a.format(*b)
print(ret) //通过字典传参数
a = "{name} is {actor}"
b = {'name':'haha', 'actor':'sb'}
ret = a.format(**b)
print(ret)
5、lambda表达式:简单函数的表达方式
lambda 形参 : 函数体
5.1、创建一个或者多个形参
5.2、执行函数体并将结果返回
func = lambda a: a+1
print(func(10))
6、内置函数
//0, None, 空列表, 空字符串, 空元祖, 空字典
//返回的值都是False
6.1、abs()
abs(-1.2) #返回 1.2 abs(1.2) #返回 1.2 abs(-11216.5) #返回 11216.5 abs(11216.5) #返回 11216.5
6.2、all() //注意:空元组、空列表返回值为True,这里要特别注意
>>> all(['a', 'b', 'c', 'd']) #列表list,元素都不为空或0
True
>>> all(['a', 'b', '', 'd']) #列表list,存在一个为空的元素
False
>>> all([0, 1,2, 3]) #列表list,存在一个为0的元素
False >>> all(('a', 'b', 'c', 'd')) #元组tuple,元素都不为空或0
True
>>> all(('a', 'b', '', 'd')) #元组tuple,存在一个为空的元素
False
>>> all((0, 1,2, 3)) #元组tuple,存在一个为0的元素
False >>> all([]) # 空列表
True
>>> all(()) # 空元组
True
6.3、any()
>>> any(['a', 'b', 'c', 'd']) #列表list,元素都不为空或0 True >>> any(['a', 'b', '', 'd']) #列表list,存在一个为空的元素 True >>> any([0, '', False]) #列表list,元素全为0,'',false False >>> any(('a', 'b', 'c', 'd')) #元组tuple,元素都不为空或0 True >>> any(('a', 'b', '', 'd')) #元组tuple,存在一个为空的元素 True >>> any((0, '', False)) #元组tuple,元素全为0,'',false False >>> any([]) # 空列表 False >>> any(()) # 空元组 False
6.4、ascii()
调用的repr()方法
6.5、bin() //二进制
#整数的情况
>>> bin(521)
#这里的显示结果形式与我们平时习惯有些差别,主要是前面多了0b,这是表示二进制的意思。
'0b1000001001'
#非整型的情况,必须包含__index__()方法切返回值为integer的类型
>>> class myType:
... def __index__(self):
... return 35 >>> myvar = myType()
>>> bin(myvar) '0b1000001001'
6.6、bool([x])
>>> bool(0)
False
>>> bool("abc")
True
>>> bool("")
False
>>> bool([])
False
>>> bool()
False
>>> issubclass(bool, int) #bool是一个subclass int
True
6.7、bytearray() //转化为字节数组
如果source为整数,则返回一个长度为source的初始化数组;
如果source为字符串,则按照指定的encoding将字符串转换为字节序列;
如果source为可迭代类型,则元素必须为[0 ,255]中的整数;
如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray。
>>> a = bytearray(3)
>>> a
bytearray(b'\x00\x00\x00')
>>> a[0] >>> a[1] >>> a[2] >>> b = bytearray("abc")
>>> b
bytearray(b'abc')
>>> b[0] >>> b[1] >>> b[2] >>> c = bytearray([1, 2, 3])
>>> c
bytearray(b'\x01\x02\x03')
>>> c[0] >>> c[1] >>> c[2] >>> d = bytearray(buffer("abc"))
>>> d
bytearray(b'abc')
>>> d[0] >>> d[1] >>> d[2]
6.8、byte() //转化为字节
6.9、callable() //检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。
>>> callable(0)
False
>>> callable("mystring")
False
>>> def add(a, b):
… return a + b
…
>>> callable(add)
True
>>> class A:
… def method(self):
… return 0
…
>>> callable(A)
True
>>> a = A()
>>> callable(a)
False
>>> class B:
… def __call__(self):
… return 0
…
>>> callable(B)
True
>>> b = B()
>>> callable(b)
True
6.10、chr(x)
返回整数i对应的ASCII字符。与ord()作用相反。
参数x:取值范围[0, 255]之间的正数。???待研究
>>> chr(97)
'a'
>>> chr(98)
'b'
>>> ord('a')
97
>>> ord('b')
98
6.11、classmethod()
指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法
类方法既可以直接类调用(C.f()),也可以进行实例调用(C().f())
>>> class C:
... @classmethod
... def f(self):
... print "This is a class method"
...
>>> C.f()
This is a class method
>>> c = C()
>>> c.f()
This is a class method
>>> class D:
... def f(self):
... print " This is not a class method "
...
>>> D.f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with D instance as first argument (got nothing instead)
>>> d = D()
>>> d.f()
This is not a class method
6.12、compile() //编译函数
6.13、complex() //复数
>>> complex(1, 2)
(1 + 2j)
#数字
>>> complex(1)
(1 + 0j)
#当做字符串处理
>>> complex("")
(1 + 0j)
#注意:这个地方在“+”号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错
>>> complex("1+2j")
(1 + 2j)
6.14、delattr(object, name) //反射的时候用
删除object对象名为name的属性
>>> class Person:
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
>>> tom = Person("Tom", 35)
>>> dir(tom)
['__doc__', '__init__', '__module__', 'age', 'name']
>>> delattr(tom, "age")
>>> dir(tom)
['__doc__', '__init__', '__module__', 'name']
6.15、dict() //字典
6.16、dir() //重要
不带参数时,返回当前范围内的变量、方法和定义的类型列表;
带参数时,返回参数的属性、方法列表。
如果参数包含方法__dir__(),该方法将被调用。
如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import struct
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'struct']
>>> dir(struct)
['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from']
>>> class Person(object):
... def __dir__(self):
... return ["name", "age", "country"]
...
>>> dir(Person)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> tom = Person()
>>> dir(tom)
['age', 'country', 'name']
6.17、divmod()
divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数。返回结果类型为tuple
>>> divmod(9,2)
(4, 1)
>>> divmod(11,3)
(3, 2)
>>> divmod(1+2j,1+0.5j)
((1+0j), 1.5j)
6.18、enumerate() //枚举,这个很厉害。
http://blog.csdn.net/churximi/article/details/51648388
对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
enumerate多用于在for循环中得到计数
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1, 1):
print index, item
>>>
1 这
2 是
3 一个
4 测试
6.19、eval(expression, globals=None, locals=None) //这个函数相当强大也相当危险,可以深入了解一下~
网址1:http://www.jb51.net/article/76375.htm
网址2:http://blog.csdn.net/caimouse/article/details/41452157
将字符串str当成有效的表达式来求值并返回计算结果
6.20、exec() //可以跟eval同时了解下,以后在补充。。。
6.21、filter(函数, 参数) //可以和map(函数, 参数)共同搞一下
def func(x):
if x>20:
return True
else :
return False li = [11, 22, 33, 44] print(list(filter(func, li)))
def func(x):
return x+100 li = [11, 22, 33, 44] print(list(map(func, li)))
filter会过滤符合函数条件的参数
map会调用参数来执行函数
6.22、float() //浮点数
6.23、format()
6.24、frozenset()
不能更改的集合
6.25、getattr()
6.26、globals()
6.27、hasattr()
6.28、hash()
python学习之函数的更多相关文章
- python学习8—函数之高阶函数与内置函数
python学习8—函数之高阶函数与内置函数 1. 高阶函数 a. map()函数 对第二个输入的参数进行第一个输入的参数指定的操作.map()函数的返回值是一个迭代器,只可以迭代一次,迭代过后会被释 ...
- python学习7—函数定义、参数、递归、作用域、匿名函数以及函数式编程
python学习7—函数定义.参数.递归.作用域.匿名函数以及函数式编程 1. 函数定义 def test(x) # discription y = 2 * x return y 返回一个值,则返回原 ...
- 从0开始的Python学习007函数&函数柯里化
简介 函数是可以重用的程序段.首先这段代码有一个名字,然后你可以在你的程序的任何地方使用这个名称来调用这个程序段.这个就是函数调用,在之前的学习中我们已经使用了很多的内置函数像type().range ...
- python学习Day10 函数的介绍(定义、组成、使用)
今日学习内容: 1.什么是函数 :函数就是一个含有特定功能的变量,一个解决某问题的工具 函数的定义:通过关键字def + 功能名字():代码体(根据需求撰写代码逻辑) 2.为什么要用函数:可以复用:函 ...
- Python学习之函数参数
上一节,我们学习了Python中是如何定义和调用函数且如何得到返回值的.在调用函数时,有的函数需要参数来启动函数,有的则无需参数.这一节我们来介绍Python中有哪些参数类型. 位置参数 在调用函数时 ...
- Python学习笔记 - 函数参数
>>> def power(x): ... return x * x ... >>> power(5) 25 >>> def power(x, n ...
- Python学习笔记—函数
函数 我们知道圆的面积计算公式为: S = πr2 当我们知道半径r的值时,就可以根据公式计算出面积.假设我们需要计算3个不同大小的圆的面积: r1 = 12.34 r2 = 9.08 r3 = 73 ...
- Python学习之函数篇
python查看对象,函数帮助文档:.__doc__,例:str.split.__doc__ 查看详细对象,函数文档:help(),例:help(str.split) 函数参数可设置默认值 如果不能提 ...
- Python学习--05函数
Python函数 函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.我们已经知道Python提供了许多内建函数,比如print().但我们 ...
- python学习:函数的学习
我们写东东的时候,往往有一些东西要频繁去复用,那么每个功能是10行代码,复用2次就是20行,这样看来我们的程序如果频繁利用某些代码的话,那么会是我们开发的东西越来越臃肿.那么好的方法有没有呢,那就是函 ...
随机推荐
- 关于Fekit的安装与测试
一. Fekit的安装 1.cmd输入指令 $ npm install fekit -g 2.初始化方法 $ fekit init 3.创建本地服务 $ fekit server 4.创建同时改端口( ...
- Thinkphp查询 1.查询方式 2.表达式查询 3.快捷查询 4.区间查询 5.组合查询 6.统计查询 7.动态查询 8.SQL 查询
1.使用字符串作为条件查询 $user = M('User'); var_dump($user->where('id=1 AND user="蜡笔小新"')->sele ...
- 学习Python的ABC模块(转)
http://yansu.org/2013/06/09/learn-Python-abc-module.html 1.abc模块作用 Python本身不提供抽象类和接口机制,要想实现抽象类,可以借助a ...
- 关于checkbox的一些问题(全选,反选,以及取值)
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- 申请使用aws的一些笔记
1. 申请可以使用asw.amazon.com/cn/,这个界面虽然是中文的,但是申请的是海外的aws. 2. 审核后会收到如下的一封邮件: 3. 剩下创建EC2和RDS的过程可以参考http://w ...
- idea使用心得(4)-踩过的坑
1.非法的表达式开始 / 需要';' / 未结束的字符串文字 表现形式: 原因/解决: 这个一定是文件编码问题:依次检查setting中的file Encodings 中的IDE ...
- SpringBoot RESTful 应用中的异常处理小结
转载:https://segmentfault.com/a/1190000006749441 @ControllerAdvice 和 @ExceptionHandler 的区别 ExceptionHa ...
- 你知道吗?使用任何HTML5开发工具都可开发iOS、Android原生App
APICloud App开发平台一直在不断升级开发工具库,这一年增加了众多开发工具.目的就是让开发者可以选择使用任何自己喜欢的HTML5开发工具去开发App.这次,APICloud把所有关于开发工具的 ...
- SpringMVC问题- MultipartConfig 配置问题以及解决方式
http://www.cnblogs.com/weilu2/p/springmvc_fileupload_with_servlet_3_0.html
- c语言的一个简单的链表
此程序为作业题: 但不忍丢弃成果: 所以记一下: 哦,对了,有一个易错点:在链表里,字符要用字符数组,不能用单个字符. #include<stdio.h>#include<stdio ...