python内置函数

查看python的内置函数

>>> 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']

作用域相关 ★★★★★

locals() 函数会以字典的类型返回当前位置的全部局部变量。若在最外面,与globals()相同。

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

a = 1

b = 2

def f1():

c = 1

print('inner locals>>>>', locals())

f1()

print('globals>>>>', globals())

print('outer locals>>>>', locals())

print(globals() == locals()) # 若在最外面,与globals()相同。结果为True

'''

inner locals>>>> {'c': 1}

globals>>>> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.sourcefileloader object at>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': 'E:\\oldboy_project\\test3.py', '__cached__': None, 'a': 1, 'b': 2, 'f1': }

outer

locals >>>> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.sourcefileloader object at>, '__spec__': None, '__annotations__': {}, '__builtins__': , '__file__': 'E:\\oldboy_project\\test3.py', '__cached__': None, 'a': 1, 'b': 2, 'f1': }

True

'''

其他相关

字符串类型代码的执行 eval,exec,complie,不建议使用★★★☆☆

eval执行的代码字符串有返回值,会接收。

exec不接收返回值。

# print(eval('x')) # not defined

x = 1

print(eval('x + 3')) # 4

print(exec('x + 3')) # None

输入输出相关 input,print ★★★★★

input:函数接受一个标准输入数据,返回为 string 类型。参数默认为None,若给了字符串,会出现提示内容。

print:打印输出。

print(*args, sep=' ', end='\n', file=sys.stdout, flush=False)

sep 是args每个参数显示的间隔。

end 是最后以什么结束。

file 接收文件句柄,可以赋值给一个文本文件。

flush 立即把内容输出到流文件,不作缓存

with open('print.txt', mode='w', encoding='utf-8') as f:

print('hello world!I am learning python.', file=f)

# 命令行中没有显示结果,而新建了一个“print.txt"文件,里面有所写的内容。

print(1, 2, 3, sep='|') # 1|2|3

内存相关 hash id ★★★☆☆

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

hash一般会得到一个长度为18的数字,

若是数值长度超过18会得到一个长度18的数字。

长度小于18会是它原来的数值。

>>> a = 100

>>> b = '100'

>>> c = True

>>> tu = (1, 2)

>>> hash(a) #数字还是它所显示的值。

100

>>> hash(b)

5677959494014640638

>>> hash(c)

1

>>> hash(tu)

3713081631934410656

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

文件操作相关

open() ★★★★★

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

模块相关__import__  ★★★☆☆

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

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

name = 'alex'

print(help(str))

调用相关

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

>>> def f1():

... print('a')

...

>>> callable(f1)

True

>>> name = 'python'

>>> callable(name)

False

查看内置属性 ★★★☆☆

dir:函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。

如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

>>> s = 'abc'

>>> dir(s)

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

迭代生成器相关

range:函数可创建一个整数对象,一般用在 for 循环中。

python2x: range(3) ---> [0,1,2] 列表

xrange(3) ---> 一个生成器

python3x: range(3) ---> range(0,3) 可迭代对象

next:内部实际使用了__next__方法,返回迭代器的下一个项目。

# 首先获得Iterator对象:

it = iter([1, 2, 3, 4, 5])

# 循环:

while True:

try:

# 获得下一个值:

x = next(it)

print(x)

except StopIteration:

# 遇到StopIteration就退出循环

break

iter:函数用来生成迭代器(讲一个可迭代对象,生成迭代器)。

from collections import Iterable

from collections import Iterator

l = [1,2,3]

print(isinstance(l,Iterable)) # True

print(isinstance(l,Iterator)) # False

l1 = iter(l)

print(isinstance(l1,Iterable)) # True

print(isinstance(l1,Iterator)) # True

基础数据类型相关

python内置函数用来打开或创建文件并返回文件对象_python内置函数相关推荐

  1. python tkinter 点击按钮选择文件,返回文件路径

    关于python tkinter 点击按钮选择文件,返回文件路径,这个方法我找了好几天,终于曲线救国实现了 首先分为两步 1.设计对话框选择文件 下面的代码搞了好几天,才发现全局变量的获取,必须放在r ...

  2. python中用于创建文件对象的是_Python内置函数________用来打开或创建文件并返回文件对象。...

    内置目前获得目标分子信息的方法不包括 药物对靶标生理活性调节而引起的毒性,函数或创称为 打开对象关于hERG通道描述不正确的选项是 建文件并反映药物分子整体亲脂性强弱的参数 是 有关structure ...

  3. python内置函数返回元素个数_Python内置函数

    Python Python开发 Python语言 Python内置函数 Python内置函数 一.内置函数 什么是内置函数? 就是python给你提供的. 拿来直接⽤的函数, 比如print, inp ...

  4. python内置函数打开文件_Python内置函数用来打开或创建文件并返回文件对象。

    误的排列关于坐姿坐位姿势良好的描要的常重述错是:内置时的是非,盘承坐姿椎间的因为常大时的受非. 函数或创工作高精轴上电动电动机上机主台上伺服伺服. 打开对象膏B可与之同连D.淡豆豉用的.黄.黄黄柏是A ...

  5. python内置函数用来打开或创建文件_Python 内置函数 _____________ 用来打开或创建文件并返回文件对象。...

    [判断题]在函数内部,既可以使用 global 来声明使用外部全局变量,也可以使用global 直接定义全局变量. [单选题]4 .等比级数 的和为( ) [填空题]7 .设 . 是二阶常系数线性微分 ...

  6. python内置函数用来打开或创建文件_2020年《python程序设计》基础知识及程序设计598题XS[含参考答案]...

    2020年<python程序设计>基础知识及程序设计 598题[含参考答案] 一.填空题 1.表达式 len('中国'.encode('utf-8')) 的值为___________.(6 ...

  7. python内置函数可以返回列表元组_Python内置函数()可以返回列表、元组、字典、集合、字符串以及range对象中元素个数....

    Python内置函数()可以返回列表.元组.字典.集合.字符串以及range对象中元素个数. 青岛远洋运输有限公司冷聚吉船长被评为全国十佳海员.()A:错B:对 有源逆变是将直流电逆变成其它频率的交流 ...

  8. python内置函数返回元素个数_python内置函数列表(list)

    一.列表list 一个队列,一个排列整齐的队伍,列表内的个体称作元素,由若干元素组成的列表,元素可以是任意对象(数字,字符串,对象,列表等) 列表内元素有顺序,可以使用索引,线性的数据结构,使用[]表 ...

  9. dict是python语言的内置对象_Python内置了字典:dict的支持

    一.dict函数 如果用dict实现,只需要一个"名字"-"成绩"的对照表,直接根据名字查找成绩,无论这个表有多大,查找速度都不会变慢.用Python写一个di ...

  10. python函数返回字符判断_Python中用startswith()函数判断字符串开头的教程

    函数:startswith() 作用:判断字符串是否以指定字符或子字符串开头 一.函数说明语法:string.startswith(str, beg=0,end=len(string)) 或strin ...

最新文章

  1. 初创企业购买企业邮箱_支持#NetNeutrality =支持设计师及其创建的初创企业
  2. 开放下载!《大促背后的前端核心业务实践》
  3. idea没有git选项
  4. c语言是非结构化程序语言_一个资深C语言工程师说C语言的重要性!直言道:不学C学什么?...
  5. 抓住指针的精髓,才算掌握了 C 语言的灵魂!
  6. STM32|4-20mA输出电路
  7. 移动互联网实时视频通讯之视频采集
  8. 使用qq邮箱服务器来实现laravel的邮件发送
  9. linux脚本vrrp_script,keepalived之vrrp_script详解
  10. Word Frequency(Leetcode192)
  11. bex5 3.7版本
  12. Android UI个性style开源组件
  13. Unity 手机VR GoogleVR 详细配置教程
  14. Ubuntu 11.10文本文档乱码
  15. 百钱百鸡(详解版)——多重循环
  16. fir滤波器算法c语言程序,FIR滤波器C语言代码
  17. 开源cms管理系统博客
  18. 协议--SCCB与IIC的区别
  19. 怎么测试t470p性能软件,ThinkPad T470p 助力耐热极限测试圆满完成
  20. 优思学院|质量管理七项原则十三项步骤

热门文章

  1. CefSharp 实现拖拉滑动验证Demo
  2. Chrome浏览器下载zoom录像
  3. 常见的几类矩阵(正交矩阵、酉矩阵、正规矩阵等)
  4. 网络篇 路由器的密码破解10
  5. 华硕B85M-D台式机主板音响没反应,更新驱动还是找不到realtek高清晰音频管理器原因及解决方案
  6. MSM8937系统启动流程
  7. “我培训完JAVA,进了美团,美团氛围特别好,就是送餐特别累”
  8. 2021年 最全面 软件测试工程师面试题及答案
  9. Nignx的修改弱密码套件
  10. [已解决]Warning: Solver not found (cplex)