python-内置 函数

内置函数

我们一起来看看python里的内置函数。什么是内置函数?就是Python给你提供的,拿来直接用的函数,比如print,input等等。截止到python版本3.6.2,现在python一共为我们提供了68个内置函数。它们就是python提供给你直接可以拿来使用的所有函数。这些函数有些我们已经用过了,有些我们还没用到过,还有一些是被封印了,必须等我们学了新知识才能解开封印的。那今天我们就一起来认识一下python的内置函数。这么多函数,我们该从何学起呢?

     内置函数    
abs() dict() help() min() setattr()
all()  dir()  hex()  next()  slice() 
any()  divmod()  id()  object()  sorted() 
ascii() enumerate()  input()  oct()  staticmethod() 
bin()  eval()  int()  open()  str() 
bool()  exec()  isinstance()  ord()  sum() 
bytearray()  filter()  issubclass()  pow()  super() 
bytes() float()  iter()  print()  tuple() 
callable() format()  len()  property()  type() 
chr() frozenset()  list()  range()  vars() 
classmethod()  getattr() locals()  repr()  zip() 
compile()  globals() map()  reversed()  __import__() 
complex()  hasattr()  max()  round()  
delattr() hash()  memoryview()  set()  

1.1作用域相关

locals :函数会以字典的类型返回当前位置的全部局部变量。

globals:函数以字典的类型返回全部全局变量。

a = 1
b = 2
print(locals())
print(globals())
# 这两个一样,因为是在全局执行的。

##########################

def func(argv):
    c = 2
    print(locals())
    print(globals())
func(3)

#这两个不一样,locals() {'argv': 3, 'c': 2}
#globals() {'__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000024409148978>, '__spec__':
None, '__file__': 'D:/lnh.python/.../内置函数.py', 'func': <function func at 0x0000024408CF90D0>,
'__name__': '__main__', '__package__': None}

  

1.2其他相关

1.2.1 字符串类型代码的执行 eval,exec,complie

  eval:执行字符串类型的代码,并返回最终结果。

eval('2 + 2')  # 4


n=81
eval("n + 4")  # 85


eval('print(666)')  # 666

  exec:执行字符串类型的代码。

s = '''
for i in [1,2,3]:
    print(i)
'''
exec(s)

  compile:将字符串类型的代码编译。代码对象能够通过exec语句来执行或者eval()进行求值。

 1 '''
 2 参数说明:   
 3 
 4 1. 参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。  
 5 
 6 2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。  
 7 
 8 3. 参数model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,model应指定为‘exec’;当source中只包含一个简单的求值表达式,model应指定为‘eval’;当source中包含了交互式命令语句,model应指定为'single'。
 9 '''
10 >>> #流程语句使用exec
11 >>> code1 = 'for i in range(0,10): print (i)'
12 >>> compile1 = compile(code1,'','exec')
13 >>> exec (compile1)
14 
15 
16 >>> #简单求值表达式用eval
17 >>> code2 = '1 + 2 + 3 + 4'
18 >>> compile2 = compile(code2,'','eval')
19 >>> eval(compile2)
20 
21 
22 >>> #交互语句用single
23 >>> code3 = 'name = input("please input your name:")'
24 >>> compile3 = compile(code3,'','single')
25 >>> name #执行前name变量不存在
26 Traceback (most recent call last):
27   File "<pyshell#29>", line 1, in <module>
28     name
29 NameError: name 'name' is not defined
30 >>> exec(compile3) #执行时显示交互命令,提示输入
31 please input your name:'pythoner'
32 >>> name #执行后name变量有值
33 "'pythoner'"
View Code

有返回值的字符串形式的代码用eval,没有返回值的字符串形式的代码用exec,一般不用compile。

1.2.2 输入输出相关 input,print

  input:函数接受一个标准输入数据,返回为 string 类型。

  print:打印输出。

 1 ''' 源码分析
 2 def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
 3     """
 4     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
 5     file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
 6     sep:   打印多个值之间的分隔符,默认为空格
 7     end:   每一次打印的结尾,默认为换行符
 8     flush: 立即把内容输出到流文件,不作缓存
 9     """
10 '''
11 
12 print(111,222,333,sep='*')  # 111*222*333
13 
14 print(111,end='')
15 print(222)  #两行的结果 111222
16 
17 f = open('log','w',encoding='utf-8')
18 print('写入文件',file=f,flush=True)
View Code

1.2.3内存相关 hash id

  hash:获取一个对象(可哈希对象:int,str,Bool,tuple)的哈希值。

print(hash(12322))
print(hash('123'))
print(hash('arg'))
print(hash('alex'))
print(hash(True))
print(hash(False))
print(hash((1,2,3)))

'''
12322
-2996001552409009098
-4637515981888139739
2311495795356652852
1
0
2528502973977326415
'''

  id:用于获取对象的内存地址。 

print(id(123))  # 1674055952
print(id('abc'))  # 2033192957072

  

1.2.3文件操作相关

  open:函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。

1.2.4模块相关__import__ 

  __import__:函数用于动态加载类和函数 。

1.2.5帮助

  help:函数用于查看函数或模块用途的详细说明。

  1 print(help(list))
  2 Help on class list in module builtins:
  3 
  4 class list(object)
  5  |  list() -> new empty list
  6  |  list(iterable) -> new list initialized from iterable's items
  7  |  
  8  |  Methods defined here:
  9  |  
 10  |  __add__(self, value, /)
 11  |      Return self+value.
 12  |  
 13  |  __contains__(self, key, /)
 14  |      Return key in self.
 15  |  
 16  |  __delitem__(self, key, /)
 17  |      Delete self[key].
 18  |  
 19  |  __eq__(self, value, /)
 20  |      Return self==value.
 21  |  
 22  |  __ge__(self, value, /)
 23  |      Return self>=value.
 24  |  
 25  |  __getattribute__(self, name, /)
 26  |      Return getattr(self, name).
 27  |  
 28  |  __getitem__(...)
 29  |      x.__getitem__(y) <==> x[y]
 30  |  
 31  |  __gt__(self, value, /)
 32  |      Return self>value.
 33  |  
 34  |  __iadd__(self, value, /)
 35  |      Implement self+=value.
 36  |  
 37  |  __imul__(self, value, /)
 38  |      Implement self*=value.
 39  |  
 40  |  __init__(self, /, *args, **kwargs)
 41  |      Initialize self.  See help(type(self)) for accurate signature.
 42  |  
 43  |  __iter__(self, /)
 44  |      Implement iter(self).
 45  |  
 46  |  __le__(self, value, /)
 47  |      Return self<=value.
 48  |  
 49  |  __len__(self, /)
 50  |      Return len(self).
 51  |  
 52  |  __lt__(self, value, /)
 53  |      Return self<value.
 54  |  
 55  |  __mul__(self, value, /)
 56  |      Return self*value.n
 57  |  
 58  |  __ne__(self, value, /)
 59  |      Return self!=value.
 60  |  
 61  |  __new__(*args, **kwargs) from builtins.type
 62  |      Create and return a new object.  See help(type) for accurate signature.
 63  |  
 64  |  __repr__(self, /)
 65  |      Return repr(self).
 66  |  
 67  |  __reversed__(...)
 68  |      L.__reversed__() -- return a reverse iterator over the list
 69  |  
 70  |  __rmul__(self, value, /)
 71  |      Return self*value.
 72  |  
 73  |  __setitem__(self, key, value, /)
 74  |      Set self[key] to value.
 75  |  
 76  |  __sizeof__(...)
 77  |      L.__sizeof__() -- size of L in memory, in bytes
 78  |  
 79  |  append(...)
 80  |      L.append(object) -> None -- append object to end
 81  |  
 82  |  clear(...)
 83  |      L.clear() -> None -- remove all items from L
 84  |  
 85  |  copy(...)
 86  |      L.copy() -> list -- a shallow copy of L
 87  |  
 88  |  count(...)
 89  |      L.count(value) -> integer -- return number of occurrences of value
 90  |  
 91  |  extend(...)
 92  |      L.extend(iterable) -> None -- extend list by appending elements from the iterable
 93  |  
 94  |  index(...)
 95  |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 96  |      Raises ValueError if the value is not present.
 97  |  
 98  |  insert(...)
 99  |      L.insert(index, object) -- insert object before index
100  |  
101  |  pop(...)
102  |      L.pop([index]) -> item -- remove and return item at index (default last).
103  |      Raises IndexError if list is empty or index is out of range.
104  |  
105  |  remove(...)
106  |      L.remove(value) -> None -- remove first occurrence of value.
107  |      Raises ValueError if the value is not present.
108  |  
109  |  reverse(...)
110  |      L.reverse() -- reverse *IN PLACE*
111  |  
112  |  sort(...)
113  |      L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
114  |  
115  |  ----------------------------------------------------------------------
116  |  Data and other attributes defined here:
117  |  
118  |  __hash__ = None
119 
120 None
121 
122 Process finished with exit code 0
View Code

1.2.6调用相关

  callable:函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。

 1 >>>callable(0)
 2 False
 3 >>> callable("runoob")
 4 False
 5  
 6 >>> def add(a, b):
 7 ...     return a + b
 8 ... 
 9 >>> callable(add)             # 函数返回 True
10 True
11 >>> class A:                  #
12 ...     def method(self):
13 ...             return 0
14 ... 
15 >>> callable(A)               # 类返回 True
16 True
17 >>> a = A()
18 >>> callable(a)               # 没有实现 __call__, 返回 False
19 False
20 >>> class B:
21 ...     def __call__(self):
22 ...             return 0
23 ... 
24 >>> callable(B)
25 True
26 >>> b = B()
27 >>> callable(b)               # 实现 __call__, 返回 True
View Code

1.2.7查看内置属性

  dir:函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

1 >>>dir()   #  获得当前模块的属性列表
2 ['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice']
3 >>> dir([ ])    # 查看列表的方法
4 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
View Code

猜你喜欢

转载自www.cnblogs.com/liuye1990/p/9203855.html