python之路 内置函数,装饰器

一、内置函数

#绝对值
abs()
#所有值都为真才为真
all()
#只要有一个值为真就为真
any()
#10进制转成二进制
bin()
#10进制转成八进制
oct()
#10进制转成十六进制
hex()
#布尔值
bool()
#字符转换成字节
bytes()
#字节转换成字符
str()

#对文件的操作
open()
#基本流程
#打开文件
op_file=open("file name","rwb+")
#操作文件
op_file.operation()
#关闭文件
op_file.close()

#检查函数是否可以被调用
callable()
#通过字节数查找Ascii中的字符
chr()
#通过Ascii中的字符查找字节
ord()
#随机数函数
random()
#把字符串编译成Python代码
compile()
#接收字符串,讲字符串当成表达式,有返回值
eval()
#执行Python代码,没有返回值
exec()
#快速获取对象提供的功能
dir()
#快速获取帮助
help()
#分页函数
divmod()
#判断对象为谁的实例是否为真
isinstacnce()
#函数返回值True,讲元素添加到结果中
filter()
#将函数返回值添加到结果中
map()
#不可变集合(未讲到)
frozenset()
#变为浮点数
float()
#所有全局变量都放在globals中
globals()
#所有局部变量都放在locals中
locals()
#生成hash值,把对象转换成hash值,一般用于字典中的key
hash()
#求最大值
max()
#求最小值
min()
#求和
sum()
#查看内存地址
memoryview()
#求次方
pow()
#范围函数
range()
#反转函数
reversed()
#四舍五入
round()
#切片
slice()
#排序
sorted()
#判断对象是什么类型
type()
#将不同元素的列表或元组(有序的)索引相同的组合成一个元祖,如果索引有差异则不显示
zip()

 1、abs

1 #数字的绝对值
2 >>> abs(-100)
3 100
4 >>> abs(100) 
5 100

2、bool

1 #判断是真是假
2 >>> bool(0)
3 False
4 >>> bool(1)
5 True
6 >>> bool(2)
7 True
8 >>> bool("")
9 False

3、all

1 #所有为真才为真
2 >>> all('123')
3 True
4 >>> all([0, 1])
5 False
6 >>> all([1, 2])
7 True

4、any

1 #有一个为真即为真
2 >>> any('123')
3 True
4 >>> any([0, 1])
5 True
6 >>> any([0, ''])
7 False

5、bin

#0b表示10进制
>>> bin(10)
'0b1010'

6、oct

1 #0o表示10进制
2 >>> oct(10)
3 '0o12'

7、hex

1 #0x表示16进制
2 >>> hex(10)
3 '0xa'

8、bytes

#将字符转换成字节
>>> bytes("你好世界",encoding="utf-8")
b'\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c'

9、str

#将字节转换成字符串
>>> str(b'\xe4\xbd\xa0\xe5\xa5\xbd\xe4\xb8\x96\xe7\x95\x8c',encoding="utf-8")  
'你好世界'

10、callable

1 >>> import tab
2 >>> def foo():
3 ...     print("allright")
4 ... 
5 #判断示例函数可否被调用
6 >>> callable(foo)
7 True

11、chr

1 #常用大写字母 ascii A-Z uncode 65-90
2 #常用小写字母 ascii a-z uncode 97-122
3 #常用数字 ascii 0-9  uncode 48-57
4 >>> chr(65)
5 'A'
6 >>> chr(90)
7 'Z'

12、ord()

1 #常用大写字母 ascii A-Z uncode 65-90
2 #常用小写字母 ascii a-z uncode 97-122
3 #常用数字 ascii 0-9  uncode 48-57
4 >>> ord("A")
5 65
6 >>> ord("Z")
7 90

13、random()

1 >>>import random
2 #在指定的范围内产生随机数
3 >>> random.randrange(20,40)
4 29
5 >>> random.randrange(20,40)
6 37

14、compile()

 1 >>> string="print(123)"
 2 #将字符串编译成Python代码(后面为固定格式)
 3 #编译格式"exec"(编译成Python代码)、"eval"(编译成表达式)、"single"(通常为当行程序)
 4 >>> result=compile(string,"<string>","exec")
 5 >>> print(string)
 6 print(123)
 7 >>> print(result)
 8 <code object <module> at 0x7fd1ee9aa660, file "<string>", line 1>
 9 #编译成Python代码后使用exec执行
10 >>> exec(result)
11 123
12 #编译成Python代码后使用eval执行
13 >>> eval(result)
14 123

15、eval()

1 #与exec的区别在与eval有返回值
2 #eval() arg 1 must be a string, bytes or code object
3 >>> result=eval("8*8")
4 >>> print(result)
5 64

16、dir()

1 #获取str可以的使用的方法
2 >>> print(dir(str))
3 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__' ****** 'title', 'translate', 'upper', 'zfill']
4  

17、help()

 1 #获取字符串replace的用法
 2 >>> help(str.replace)
 3 
 4 Help on method_descriptor:
 5 
 6 replace(...)
 7     S.replace(old, new[, count]) -> str
 8     
 9     Return a copy of S with all occurrences of substring
10     old replaced by new.  If the optional argument count is
11     given, only the first count occurrences are replaced.
12 
13 #使用q退出

18、divmod()

1 #获取余数(除数,被除数)
2 >>> ret1,ret2=divmod(100,10)
3 >>> print(ret1,ret2)
4 10 0

19、isinstance()

1 >>> string="yorick"
2 #判断对象是谁的实例是否为真
3 #判断string是不是一个字符串
4 >>> isinstance(string,str)
5 True

20、filter()

 1 >>> def foo(arg):
 2 ...     if arg > 22:
 3 ...         return True
 4 ... 
 5 >>> n_list=[11,22,33,44,55]
 6 #函数返回值True,将元素添加到结果中
 7 >>> result=filter(foo,n_list)
 8 #python3.0经过调优,不直接将结果输出出来,防止操作的内容过多
 9 >>> print(result)
10 <filter object at 0x7f76f259a4a8>
11 >>> print(list(result))
12 [33, 44, 55]
13 
14 #使用lambda表达式
15 >>> n_list=[11,22,33,44,55]  
16 >>> result = filter(lambda par: par > 22,n_list)
17 >>> print(list(result))
18 [33, 44, 55]

21、map()

>>> n_list=[11,22,33,44,55]                     
>>> def foo(arg):
...     return arg + 100
... 
#将返回的结果添加到result中组成一个列表
>>> result = map(foo,n_list)
>>> print(list(result))
[111, 122, 133, 144, 155]

>>> n_list=[11,22,33,44,55] 
>>> def foo(arg):
...     return False
... 
#将返回的结果添加到result中组成一个列表
>>> result = map(foo,n_list)
>>> print(list(result))     
[False, False, False, False, False]

22、float()

 1 >>> string="65.20"
 2 #将字符转换成浮点型
 3 >>> float(string)
 4 65.2
 5 >>> type(float(string))
 6 <class 'float'>
 7 >>> type(string)
 8 <class 'str'>
 9 
10 >>> string=5
11 >>> type(string)
12 <class 'int'>
13 #将整数型转换成浮点型
14 >>> float(string)
15 5.0
16 >>> print(type(float(string)))
17 <class 'float'>

23、globals()、locals

>>> def foo():          
...     n_list=[1234567]
...     print("This is Begin Globals".center(40,"-"))
#打印全局变量
...     print(globals())                             
...     print("This is Begin locals".center(40,"-")) 
#打印局部变量
...     print(locals())                              
... 
>>> foo()
---------This is Begin Globals----------
{'string': 5, 'tab': <module 'tab' from '/usr/local/python3.5/lib/python3.5/site-packages/tab.py'>, 'result': <map object at 0x7f76f259a550>, '__spec__': None, '__package__': None, 'n_list': [11, 22, 33, 44, 55], 'foo': <function foo at 0x7f76f256e9d8>, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__doc__': None}
----------This is Begin locals----------
{'n_list': [1234567]}

24、hash()

1 #较多应用为字典的key值
2 
3 #获取单个字符的hash值
4 >>> hash("a")
5 -6417969680733924203
6 
7 #获取长度较长的hash值
8 >>> hash("sssssssssssssssssssssssssssssssssssssssssssssssssssssss")
9 1067091481945040275

25、max()、min()、sum()

 1 #注意:必须为数字
 2 #max比较一个可迭代的序列中的最大值
 3 >>> max(11,222,3344,555)
 4 3344
 5 >>> max([11,2233,44,5566,664,23])
 6 5566
 7 
 8 #min比较一个可迭代的序列中的最小值
 9 >>> min(11,222,3344,555)         
10 11
11 >>> min([11,2233,44,5566,664,23])
12 11
13 
14 #sum将一个可迭代的序列求和[不能再sum()语法中添加过多的对象]
15 >>> sum((11,22,33,44))
16 110
17 >>> sum([11,22,33,44])
18 110
19 >>> sum({11,22,33,44})
20 110

26、pow

1 >>> pow(2,10)
2 1024
3 >>> 2**10
4 1024

27、range()

 1 #默认起始位置为0
 2 >>> for i in range(10):
 3 ...     print(i)
 4 ... 
 5 0
 6 1
 7 2
 8 3
 9 4
10 5
11 6
12 7
13 8
14 9

28、reversed()

1 >>> o_list=["11","22","33","44","55"]
2 >>> o_list
3 ['11', '22', '33', '44', '55']
4 >>> n_list=reversed(o_list)
5 >>> n_list
6 <list_reverseiterator object at 0x7f76f259a630>
7 >>> print(list(n_list))
8 ['55', '44', '33', '22', '11']

29、round()

1 #5舍去
2 >>> round(4.5)
3 4
4 #6入
5 >>> round(4.6)
6 5

30、sorted()

1 >>> o_list=["Eric","Yorick","Alex","Bill"]
2 >>> o_list
3 ['Eric', 'Yorick', 'Alex', 'Bill']
4 >>> n_list=sorted(o_list)
5 >>> n_list
6 ['Alex', 'Bill', 'Eric', 'Yorick']

31、type()

1 #判断对象的类型
2 >>> foo1="string"
3 >>> foo2="123"
4 >>> foo3=12345
5 >>> foo4={1:"2015"}
6 >>> type(foo1),type(foo2),type(foo3),type(foo4)
7 (<class 'str'>, <class 'str'>, <class 'int'>, <class 'dict'>)

32、zip()

1 >>> list1=["Yorick","223123**12323123","xxx"]
2 >>> list2=["is","123213*231231","oooo"]
3 >>> list3=["God","89898989*898989","xxxxx"]
4 #将不同元素的列表或元组(有序的)索引相同的组合成一个元祖,如果索引有差异则不显示
5 >>> print(list(zip(list1,list2,list3)))
6 [('Yorick', 'is', 'God'), ('223123**12323123', '123213*231231', '89898989*898989'), ('xxx', 'oooo', 'xxxxx')]

二、装饰器

def outer(func):
    def inner():
        print('log')
        return func()
    return inner

@outer
def f1():
    print('f1')

@outer
def f2():
    print('f2')

@outer
def f3():
    print('f3')
#自动执行outer函数并且将其下面的函数名f1当做参数传递
#将outer函数的返回值,重新赋值给f1
def outer(func):
    def inner(*args,**kwargs):
        print('before')
        r = func(*args,**kwargs)#func==老的f1
        print('after')
        return r #获取f1的返回值
    return inner

@outer
def f1(*args,**kwargs):
    print('aaaa')
    return '是是是'

 

posted @ 2016-06-04 11:51  zhang_kk  阅读(453)  评论(0编辑  收藏  举报