python 内置函数使用方法,python内置函数

python 内置函数使用方法,python内置函数

 dir(__builtins__)

1、’abs’, 对传入参数取绝对值

abs(x, /)
    Return the absolute value of the argument.

1 >>> abs(10)
2 10
3 >>> abs(-10)
4 10

2、’all’,  用于判断给定的可迭代参数 iterable 中的所有元素是否不为
0、”、False 或者 iterable 为空,如果是返回 True,否则返回 False。

all(iterable, /)
    Return True if bool(x) is True for all values x in the iterable.

    If the iterable is empty, return True.

1 >>> all([1, 2])
2 True
3 >>> all([1, 0])
4 False
5 >>> all([])
6 True

3、’any’, 用于判断给定的可迭代参数 iterable
是否全部为空对象,如果都为空、0、false,则返回
False,如果不都为空、0、false,则返回 True。

any(iterable, /)
    Return True if bool(x) is True for any x in the iterable.

    If the iterable is empty, return False.

1 >>> any([1, 2])
2 True
3 >>> any([1, 0])
4 True
5 >>> any([])
6 False

4、’ascii’, 自动执行传入参数的_repr_方法(将对象转换为字符串)

ascii(obj, /)
    Return an ASCII-only representation of an object.

    As repr(), return a string containing a printable representation of an
    object, but escape the non-ASCII characters in the string returned by
    repr() using \x, \u or \U escapes. This generates a string similar
    to that returned by repr() in Python 2.

1 >>> ascii(10)
2 '10'
3 >>> ascii('abc')
4 "'abc'"
5 >>> ascii('你妈嗨')
6 "'\u4f60\u5988\u55e8'"

5、’bin’, 返回一个整数 int 或者长整数 long int 的二进制表示。

bin(number, /)
    Return the binary representation of an integer.

1 >>> bin(1024)
2 '0b10000000000'

6、’bool’,  函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。

7、’bytearray’, 返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围:
0 <= x < 256。

8、’bytes’, 字符串转换成字节流。第一个传入参数是要转换的字符串,第二个参数按什么编码转换为字节
eg. bytes(s,encoding = ‘utf-8’) , bytes(s,encoding = ‘gbk’)  
 1个字节占8位;utf-8编码格式下,一个汉字占3个字节;gbk编码格式下,一个汉字占2个字节

9、’callable’, 用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。对于函数,
方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。

callable(obj, /)
    Return whether the object is callable (i.e., some kind of function).

    Note that classes are callable, as are instances of classes with a
    __call__() method.

1 >>> callable(int)
2 True
3 >>> class Test():
4 ...     def __call__(self):
5 ...         return 1
6 ... 
7 >>> test = Test()
8 >>> test()
9 1

10、’chr’, 数字转字符

chr(i, /)
    Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

1 l = []
2 for i in range(0x10ffff + 1):
3     try:
4         print(i, chr(i), end=" ")
5     except:
6         l.append(i)
7 
8 print(l)
9 print(len(l))

11、’classmethod’, 修饰符对应的函数不需要实例化,不需要 self
参数,但第一个参数需要是表示自身类的 cls
参数,可以来调用类的属性,类的方法,实例化对象等。

12、’compile’, 接收.py文件或字符串作为传入参数,将其编译成python字节码

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
    Compile source into a code object that can be executed by exec() or eval().

    The source code may represent a Python module, statement or expression.
    The filename will be used for run-time error messages.
    The mode must be 'exec' to compile a module, 'single' to compile a
    single (interactive) statement, or 'eval' to compile an expression.
    The flags argument, if present, controls which future statements influence
    the compilation of the code.
    The dont_inherit argument, if true, stops the compilation inheriting
    the effects of any future statements in effect in the code calling
    compile; if absent or false these statements do influence the compilation,
    in addition to any features explicitly specified.

>>> str = "for i in range(0,10): print(i)" 
>>> c = compile(str,'','exec')
>>> c
<code object <module> at 0x00000000022EBC00, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str, '', 'eval')
>>> a
<code object <module> at 0x00000000022EB5D0, file "", line 1>
>>> eval(a)
17

13、’complex’, 函数用于创建一个值为 real + imag * j
的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。

14、’copyright’, 

15、’credits’, 

16、’delattr’, 用于删除属性。

delattr(obj, name, /)
    Deletes the named attribute from the given object.

    delattr(x, 'y') is equivalent to ``del x.y''

>>> class Test():
...     def __init__(self):
...         self.name  = 'w'
...         self.age = 20
... 
>>> test = Test()
>>> test.name
'w'
>>> test.age
20
>>> delattr(test, 'name')
>>> test.name
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'name'
>>> del test.age
>>> test.age
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'age'

17、’dict’, 用于创建一个字典。

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

dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

1 >>> dir()
2 ['__builtins__', '__doc__', '__name__']
3 >>> dir(list)
4 ['__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']

19、’divmod’,
 把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a %
b)。

1 divmod(x, y, /)
2     Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.

1 >>> divmod(10, 3)
2 (3, 1)

20、’dreload’, 重新载入模块。

reload(module, exclude=['sys', 'os.path', 'builtins', '__main__'])
    Recursively reload all modules used in the given module.  Optionally
    takes a list of modules to exclude from reloading.  The default exclude
    list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
    display, exception, and io hooks.

21、’enumerate’, 用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在
for 循环当中。

22、’eval’, 用来执行一个字符串表达式,并返回表达式的值。

eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.

    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

1 >>> x = 10
2 >>> eval('3 * x')
3 30

23、’exec’, 执行python代码(可以是编译过的,也可以是未编译的),没有返回结果(返回None)

1 exec(source, globals=None, locals=None, /)
2     Execute the given source in the context of globals and locals.
3     
4     The source may be a string representing one or more Python statements
5     or a code object as returned by compile().
6     The globals must be a dictionary and locals can be any mapping,
7     defaulting to the current globals and locals.
8     If only globals is given, locals defaults to it.

1 >>> exec(compile("print(123)","<string>","exec"))
2 123
3 >>> exec("print(123)")
4 123

24、’filter’, 用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回
True 或 False,最后将返回 True 的元素放到新列表中。

25、’float’, 用于将整数和字符串转换成浮点数。

26、’format’, #字符串格式化

format(value, format_spec='', /)
    Return value.__format__(format_spec)

    format_spec defaults to the empty string

1 >>> "{1} {0} {1}".format("hello", "world")
2 'world hello world'
3 >>> "网站名:{name}, 地址 {url}".format(name="教程", url="www.nimahai.com")
4 '网站名:教程, 地址 www.nimahai.com'

27、’frozenset’, 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。

28、’getattr’, 用于返回一个对象属性值。

getattr(...)
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.

>>> class Test():
...     def __init__(self):
...         self.name = 'w'
... 
>>> test = Test()
>>> getattr(test, 'name')
'w'
>>> test.name
'w'
>>> getattr(test, 'age')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'age'
>>> test.age
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'age'
>>> getattr(test, 'age', 20)
20
>>> test.age
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Test' object has no attribute 'age'

29、’globals’, 返回一个字典,包括所有的全局变量与它的值所组成的键值对

globals()
    Return the dictionary containing the current scope's global variables.

    NOTE: Updates to this dictionary *will* affect name lookups in the current
    global scope and vice-versa.

a =100
print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000000001E867F0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '1.py', '__cached__': None, 'a': 100}

‘hasattr’,
‘hash’, 对传入参数取哈希值并返回
‘help’, 接收对象作为参数,更详细地返回该对象的所有属性和方法
‘hex’, 接收一个十进制,转换成十六进制
‘id’, 返回内存地址,可用于查看两个变量是否指向相同一块内存地址
‘input’,
 提示用户输入,返回用户输入的内容(不论输入什么,都转换成字符串类型)
‘int’, 转换为整型
‘isinstance’, 判断对象是否是某个类的实例. e.g.
isinstance([1,2,3],list)
‘issubclass’, 查看这个类是否是另一个类的派生类,如果是返回True,否则返回False
‘iter’,
‘len’, 返回字符串长度,在python3中以字符为单位,在python2中以字节为单位
‘license’,
‘list’, 转换为列表类型
‘locals’, 返回一个字典,包括所有的局部变量与它的值所组成的键值对
‘map’, 对可迭代的每一个元素,将其作为实参传入函数,将每一次调用函数返回的结果都添加到map的返回值中。e.g.
tuple(map(lambda a:a+1,(1,2,3))) 返回(2,3,4)
‘max’, 接收序列化类型数据,返回其中值最大的元素
‘memoryview’, 查看内存地址
‘min’,返回其中值最小的元素
‘next’,
‘object’,
‘oct’, 接收一个十进制,转换成八进制
‘open’,
‘ord’, 字母转数字,查看ASCII码表
‘pow’, 求次方,返回x**y的结果
‘print’,
‘property’,  获取对象的所有属性
‘range’, 获取随机数或随机字符 eg. range(10) 从0到10的随机数
‘repr’, 执行传入对象中的_repr_方法
‘reversed’, 对序列化类型数据反向排序,返回一个新的对象。注意与对象的reverse方法区别,后者是就地改变对象
’round’, 返回四舍五入后的结果
‘set’, 转换为集合类型
‘setattr’,
‘slice’, 对序列化类型数据切片,返回一个新的对象。eg.
slice(起始下标,终止下标,步长),步长默认为1
‘sorted’, 对序列化类型数据正向排序,返回一个新的对象。注意与对象的sort方法区别,后者是就地改变对象
‘staticmethod’, 返回静态方法
‘str’, 字节转换成字符串。第一个传入参数是要转换的字节,第二个参数是按什么编码转换成字符串
‘sum’,
‘super’, 返回基类
‘tuple’, 转换为元组类型
‘type’, 返回对象类型
‘vars’, 返回当前模块中的所有变量
‘zip’ 接收多个序列化类型的数据,对各序列化数据中的元素,按索引位置分类成一个个元组

 

内置函数使用方法,python内置函数
dir(__builtins__) 1、’abs’,对传入参数取绝对值 abs(x, /) Return the
absolute value of the argument. 1 abs(10 ) 2 10 3…

相关文章

发表评论