一 内置函数

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'fibonacci': <function fibonacci at 0x000001B7F6F43E18>, 'fib': <generator object fibonacci at 0x000001B7F7119990>, 'isgeneratorfunction': <function isgeneratorfunction at 0x000001B7F736BC80>, 'Iterable': <class 'collections.abc.Iterable'>}
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

  abs():取绝对值

  all():接收一个可迭代对象,如bool值都是True,则返回True,否则False

    all([1,1,1])  True;all([1,1,0])  False

  any():接收一个可迭代对象;如有一个bool值为True,则返回True,否则False。

    any([0,0,1])  True;any([0,0,0])   False

  ascii();调用对象的__repr__()方法,获得该方法的返回值。

  repr():调用对象所属类的__repr__方法,与print类似

>>> s="haha"
>>> ascii(s)
"'haha'"
>>> a=[1,2,3]
>>> ascii(a)
'[1, 2, 3]'

  bin(),oct(),hex():

  bool():

  bytearray():

    实例化一个bytearray类型的对象。参数可以是字符串、整数或者可迭代对象。bytearray是Python内置的一种可变的序列数据类型,具有大多数bytes类型同样的方法。

  当参数是字符串的时候,需要指定编码类型。

  当参数是整数时,会创建以该整数为长度,包含同样个数空的bytes对象的数组。

  当参数是个可迭代的对象时,该对象必须是一个取值范围0 <= x < 256的整数序列

>>> a = bytearray("asdff",encoding='utf-8')
>>> a
bytearray(b'asdff')
>>> b = bytearray(10)
>>> b
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> d = bytearray([1,2,3])
>>> d
bytearray(b'\x01\x02\x03')
>>> e = bytearray([1,2,300])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: byte must be in range(0, 256)

  bytes():str():

  callable():判断对象是否可被调用。如对象具有__call__方法,则可被调用。

  chr():返回某个十进制数对应的ASCII字符,例如:chr(99) = ‘c’。它可以配合random.randint(65,91)随机方法,生成随机字符,用于生产随机验证码。

    

import random
for i in range(10):
    a = random.randint(65,91)
    c = chr(a)
    print(c)

W
S
B
C
X
G
L
J
K
[

  ord():与chr()相反,返回某ASCII字符对应的十进制数。

  compile():将字符串编译成Python能识别或执行的代码。 也可以将文件读成字符串再编译。

  eval():将字符串直接解读并执行。

  exec():执行字符串或compile方法编译过的字符串,没有返回值

>>> s = "print('helloworld')"
>>> r = compile(s,"<string>","exec")
>>> r
<code object <module> at 0x000001B7F7395C00, file "<string>", line 1>
>>> r()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'code' object is not callable
>>> exec(r)
helloworld
>>> eval(r)
helloworld

  enumerate():枚举函数,在迭代对象时,添加序列号;默认从0开始。

>>> dic = {'k1':'v1','k2':'v2','k3':'v3'}
>>> for i,key in enumerate(dic,1):
...     print (i,"\t",key)
...
1        k1
2        k2
3        k3

  frozenset():返回一个不能增加和修改的集合类型对象。

>>> a=[1,2,3]
>>> b = frozenset(a)
>>> b
frozenset({1, 2, 3})
>>> b.append(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'append'

  hash():参数为不可变对象。生成哈希值。

>>> hash('i am jack')
328063707655366170
>>> hash(1)
1
>>> hash(100000)
100000
>>> hash([1,2,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash((1,2,3))
2528502973977326415

  help();id():input();isinstance();

  issubclass():issubclass(a,b),判断a是否b的子类

  iter():制造迭代器

  len();

  locals():返回当前可用的局部变量。

>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'fibonacci': <function fibonacci at 0x000001B7F6F43E18>, 'fib': <generator object fibonacci at 0x000001B7F7119990>, 'isgeneratorfunction': <function isgeneratorfunction at 0x000001B7F736BC80>, 'Iterable': <class 'collections.abc.Iterable'>, 's': "print('helloworld')", 'a': [1, 2, 3], 'b': frozenset({1, 2, 3}), 'd': bytearray(b'\x01\x02\x03'), 'random': <module 'random' from 'C:\\ProgramData\\Anaconda3\\lib\\random.py'>, 'r': <code object <module> at 0x000001B7F7395C00, file "<string>", line 1>, 'dic': {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}, 'i': 3, 'key': 'k3'}

  max();min()

  memoryview(obj):返回obj的内存视图对象;obj只能是bytes或bytesarrar类型

>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
>>> v[5]
103
>>> v[1:4]
<memory at 0x000001B7F72BAA08>
>>> bytes(v[1:4])
b'bce'

  vars();与dir()类似;dir()直返key,vars()返回key和value

>>> dir()
['Iterable', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'd', 'dic', 'fib', 'fibonacci', 'i', 'isgeneratorfunction', 'key', 'r', 'random', 's', 'v']
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'fibonacci': <function fibonacci at 0x000001B7F6F43E18>, 'fib': <generator object fibonacci at 0x000001B7F7119990>, 'isgeneratorfunction': <function isgeneratorfunction at 0x000001B7F736BC80>, 'Iterable': <class 'collections.abc.Iterable'>, 's': "print('helloworld')", 'a': [1, 2, 3], 'b': frozenset({1, 2, 3}), 'd': bytearray(b'\x01\x02\x03'), 'random': <module 'random' from 'C:\\ProgramData\\Anaconda3\\lib\\random.py'>, 'r': <code object <module> at 0x000001B7F7395C00, file "<string>", line 1>, 'dic': {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}, 'i': 3, 'key': 'k3', 'v': <memory at 0x000001B7F72BA948>}

  map;macp(func,iterable);filter(func,iterable),zip()

  __import__(name):name为要导入的库的名称的字符串

>>> t=__import__('time')
>>> print(t.time())
1534841246.2802804

 

posted on 2018-08-21 16:48  voldermorter  阅读(105)  评论(0)    收藏  举报