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()
最新文章
- Android(Linux)控制GPIO的方法及实时性分析
- Scala:映射和元组
- Win8+VMware12+CentOS7网络设置
- Java命名规则总结
- git相关
- 如何添加win10命令提示符字体,美化显示效果
- C#创建桌面快捷方式 和 开机启动
- UIBarButtonItem变弹簧
- c++ 普通高精乘
- “未能加载文件或程序集file:///E:/MoneySet.dll或它的某一个依赖项,试图加载格式不正确的程序,行203,位置5. 文件:MReportSet.resx”,
- asp.net 导入
- android 休眠唤醒机制分析(二) — early_suspend
- java常用包
- uva 10714 Ants(贪心)
- Django中ModelForm应用
- elasticsearch 搜索不支持单词的部分进行匹配
- Form.Close跟Form.Dispose
- xamarin android制作圆角边框
- Python网络数据采集PDF
- JavaEE-tomcat8.5的启动方法
热门文章
- Sourceinsight最佳配色方案及颜色字体调整方法
- 使用bootstrap 弹出效果演示
- Linux 升级修改libc gcc 文件名称,导致执行命令失效问题解决
- ORM系列之二:EF(4) 约定、注释、Fluent API
- canvas 拖拽实现
- mysql关于排序值的问题
- Selenium2学习-040-JavaScript弹出框(alert、confirm、prompt)操作演示实例
- Smokeping安装教程
- 解决Office互操作错误";检索COML类工厂中 CLSID为 {xxx}的组件时失败,原因是出现以下错误: 80070005";
- ps commad