内置函数1

2018-08-21  本文已影响12人  hiDaLao

内置函数


  python作为一门好用的语言,其内置了许多函数可直接供程序员们调用,以进一步减轻代码负担。python中的内置函数也是在不断发展的,截止到3.6.2版本,python共有内置函数68个。本文将其共分为四类:

见以下详细介绍:

作用域



# a = 'hiDaLao'
# b = 2
# print(globals())
# print(locals())

# 此时二者一致,因为均在全局空间
{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())"], '_oh': {}, '_dh': ['D:\\骑士python\\day13'], 'In': ['', "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())"], 'Out': {}, 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x0000019402C45208>>, 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000019403710898>, 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000019403710898>, '_': '', '__': '', '___': '', '_i': '', '_ii': '', '_iii': '', '_i1': "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())", 'a': 'hiDaLao', 'b': 2}
{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())"], '_oh': {}, '_dh': ['D:\\骑士python\\day13'], 'In': ['', "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())"], 'Out': {}, 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x0000019402C45208>>, 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000019403710898>, 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000019403710898>, '_': '', '__': '', '___': '', '_i': '', '_ii': '', '_iii': '', '_i1': "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())", 'a': 'hiDaLao', 'b': 2}
# def func():
#     a = 'hiDaLao'
#     print(globals())
#     print(locals())
# b = 1
# func()

# 此时二者不同,globals输出了当前所有全局变量(包含内置命名空间),而locals输出的则是其所在的fanc()函数中的全部局部变量{'a': 'hiDaLao'}
{'__name__': '__main__', '__doc__': 'Automatically created module for IPython interactive environment', '__package__': None, '__loader__': None, '__spec__': None, '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '_ih': ['', "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())", "def func():\n    a = 'hiDaLao'\n    print(globals())\n    print(locals())\nb = 1\nfunc()"], '_oh': {}, '_dh': ['D:\\骑士python\\day13'], 'In': ['', "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())", "def func():\n    a = 'hiDaLao'\n    print(globals())\n    print(locals())\nb = 1\nfunc()"], 'Out': {}, 'get_ipython': <bound method InteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x0000019402C45208>>, 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000019403710898>, 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x0000019403710898>, '_': '', '__': '', '___': '', '_i': "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())", '_ii': '', '_iii': '', '_i1': "\na = 'hiDaLao'\nb = 2\nprint(globals())\nprint(locals())", 'a': 'hiDaLao', 'b': 1, '_i2': "def func():\n    a = 'hiDaLao'\n    print(globals())\n    print(locals())\nb = 1\nfunc()", 'func': <function func at 0x0000019403820048>}
{'a': 'hiDaLao'}

其他相关


字符串类型代码的执行

  eval函数单看定义其实挺难理解,但如果同时借助代码来看就会非常清晰了。首先要知道的是eval函数主要作用于字符串类型,当字符串的内容为python中的可执行代码时,我们可以借助eval函数来执行改字符串类型的代码。该函数在文件处理方面大有可为。相见下面代码:

# eval
def func(x):
    return x
print('func("hiDaLao is the best")')
print(eval('func("hiDaLao is the best")'))

b = '1 + 1'
print(b)
print(eval(b))

c = '[i for i in range(1,10)]'
print(c)
print(eval(c))
func("hiDaLao is the best")
hiDaLao is the best
1 + 1
2
[i for i in range(1,10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

   exec函数eval函数的定义和用法均较为相似,但最大的不同点是exec函数只执行字符串类型的代码,不返回;而eval函数不仅执行,还会将结果返回给调用者。详细见代码:

# exec
def func1(x):
    return x

print('print("hiDaLao is the best")')      #最外层的print语句里面的所有内容均为字符串
print("---------------")

print(eval('func1("hiDaLao is the best")'))   #遇到
print("---------------")

print(exec('func1("hiDaLao is the best")'))
print("---------------")

print(eval('print("hiDaLao is the best")'))
print("---------------")

print(exec('print("hiDaLao is the best")'))
print("---------------")

exec('print("hiDaLao is the best")')
print("---------------")

eval('print("hiDaLao is the best")')
print("hiDaLao is the best")
---------------
hiDaLao is the best
---------------
None
---------------
hiDaLao is the best
None
---------------
hiDaLao is the best
None
---------------
hiDaLao is the best
---------------
hiDaLao is the best
print(exec('1 + 2'))
None
print(eval('1 + 2'))
3

  compile函数是将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值.compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1).下面详细介绍compile中的详细参数:

  1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。

  2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。

  3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。

输入输出相关

input函数之前接触的较多,不多加赘述。唯一需要注意的是input其返回的值均为字符串类型。

a = input('<<<')

print(a,type(a))
<<<(1,2,3)
(1,2,3) <class 'str'>

  print函数,print函数应该是python里面使用最多的内置函数。其源码为:def print(value,*args, sep=' ', end='\n', file=sys.stdout, flush=False),以下对其做详细介绍:

with open('print函数','w+',encoding = 'utf-8')as f:
    print(1,2,3,4,file= f)
print('------------')
print(1,2,3,4,sep = '|')
print('------------')
print(1,2,3,4,end = '_')
print(1,2,3,4)
print('------------')
------------
1|2|3|4
------------
1 2 3 4_1 2 3 4
------------

内存相关

  hash函数主要用来获取可哈希对象的哈希地址,此知识应与字典练习起来,字典的key必须为可哈希对象,这也是字典查找速度快的原因。非数字和布尔型变量的hash值为一串等长数字,其均唯一。数字的哈希地址为其本身,不可哈希的数据类型使用该函数会报错。True的哈希地址为1,False的哈希地址为0.

print(hash('haDaLao'))
print(hash('你好python'))
print(hash((1,2,3,4)))
print(hash(True))
print(hash(False))
print(hash(1))
print(hash(134657445474))
-3002480309828225705
-6276695183465522733
485696759010151909
1
0
1
134657445474

  id函数主要用来获取对象的内存地址。

print(id(123))
print(id(2))
1934389280
1934385408

文件操作相关

调用相关

# callable
def func3():
    pass
print(callable(123))
print(callable(func3))
False
True

查看内置属性

#dir
print(dir())
print('--------------')
print(dir([]))
['In', 'Out', '_', '__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_dh', '_i', '_i1', '_i10', '_i11', '_i12', '_i2', '_i3', '_i4', '_i5', '_i6', '_i7', '_i8', '_i9', '_ih', '_ii', '_iii', '_oh', 'a', 'exit', 'f', 'func3', 'get_ipython', 'quit']
--------------
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

迭代器生成器相关


# range
print([i for i in range(9)])
[0, 1, 2, 3, 4, 5, 6, 7, 8]
# iter next
i = iter([1,2,3,4,5])  #获得Iterale
while 1:
    try:
        print(next(i))
    except StopIteration:   # 遇到StopIteration就退出循环    
        break
        
1
2
3
4
5

基础数据类型相关


数字相关

数据类型

# bool  
print(bool(1 < 2 and 3 > 4 or 5 < 6 and 9 > 2 or 3 > 1))
True

int函数,当里面是数字类型时,只取整数部分。当把字符串型数字转化为int型时,只接收整数。

# int 只取整数部分,与round不同
print(int(2.3))
print(int(2.99))
print(int(3/2))
print(int('3.1'))
2
2
1



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-19-46b16cda65dd> in <module>()
      3 print(int(2.99))
      4 print(int(3/2))
----> 5 print(int('3.1'))


ValueError: invalid literal for int() with base 10: '3.1'

float类型与int型类似,complex型日常使用较少,此处不多加介绍。

进制转换

print(bin(11))
print(oct(7))
print(oct(9))
print(hex(9))
print(hex(10))
print(hex(11))
print(hex(12))
print(hex(15))
print(hex(16))
print(hex(17))
0b1011
0o7
0o11
0x9
0xa
0xb
0xc
0xf
0x10
0x11

数学运算

#abs
print(abs(1))
print(abs(-1))
print('---------')

1
1
---------
#divmod
print(divmod(4,2))
print(divmod(18,7))
(2, 0)
(2, 4)
#round
print(round(3.14159))
print(round(3.14159,3))    #保留三位小数
3
3.142
# pow
print(pow(2,5))
32
# sum
print(sum([1,2,3,4]))
print(sum([1,2,3,4],100))  #设置初始值为1000
10
110

max和min函数有共通之处,其第二个参数可接自定义参数,所以这两个函数的可定制型极强。

# max 与 min
print(min([1,-2,3,4,100,101]))
print(min([1,-2,3,4,100,101]))
print(min([1,-2,3,4,100,101],key=abs))

-2
-2
1
#需求
# [('alex',1000),('太白',18),('wusir',500)]
# 求出年龄最小的那个元组
l = [('alex',1000),('太白',18),('wusir',500)]
def func5(x):
    return x[-1]
print(min(l,key = func5))
('太白', 18)
上一篇下一篇

猜你喜欢

热点阅读