python@内置帮助系统的使用@eval@repr@str@内置函数源代码查看
文章目录
- refs
- python命令行文档
- python --help
- python help函数
- 进入帮助系统(简练的python文档系统)
- 查阅内置模块(函数/异常/对象)
- 内置类型
- 区分大小写
- 查看可用的帮助话题
- 可用的符号
- 可用模块
- 查看具体对象
- 查看指定对象函数的帮助
- eval
- repr
- 内置函数源代码查看
- 某些内置函数无法直接通过IDE查看
refs
- str() vs repr() in Python - GeeksforGeeks
python命令行文档
- 3.11.1 Documentation (python.org)
python --help
python --help
usage: D:\Program Files\Python310\python.exe [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): -b : issue warnings about str(bytes_instance), str(bytearray_instance)and comparing bytes/bytearray with str. (-bb: issue errors) -B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x -c cmd : program passed in as string (terminates option list) -d : turn on parser debugging output (for experts only, only works ondebug builds); also PYTHONDEBUG=x -E : ignore PYTHON* environment variables (such as PYTHONPATH) -h : print this help message and exit (also -? or --help) -i : inspect interactively after running script; forces a prompt evenif stdin does not appear to be a terminal; also PYTHONINSPECT=x -I : isolate Python from the user's environment (implies -E and -s) -m mod : run library module as a script (terminates option list) -O : remove assert and __debug__-dependent statements; add .opt-1 before.pyc extension; also PYTHONOPTIMIZE=x -OO : do -O changes and also discard docstrings; add .opt-2 before.pyc extension -q : don't print version and copyright messages on interactive startup -s : don't add user site directory to sys.path; also PYTHONNOUSERSITE -S : don't imply 'import site' on initialization -u : force the stdout and stderr streams to be unbuffered;this option has no effect on stdin; also PYTHONUNBUFFERED=x -v : verbose (trace import statements); also PYTHONVERBOSE=xcan be supplied multiple times to increase verbosity -V : print the Python version number and exit (also --version)when given twice, print more information about the build -W arg : warning control; arg is action:message:category:module:linenoalso PYTHONWARNINGS=arg -x : skip first line of source, allowing use of non-Unix forms of #!cmd -X opt : set implementation-specific option. The following options are available:-X faulthandler: enable faulthandler-X showrefcount: output the total reference count and number of usedmemory blocks when the program finishes or after each statement in theinteractive interpreter. This only works on debug builds-X tracemalloc: start tracing Python memory allocations using thetracemalloc module. By default, only the most recent frame is stored in atraceback of a trace. Use -X tracemalloc=NFRAME to start tracing with atraceback limit of NFRAME frames-X importtime: show how long each import takes. It shows module name,cumulative time (including nested imports) and self time (excludingnested imports). Note that its output may be broken in multi-threadedapplication. Typical usage is python3 -X importtime -c 'import asyncio'-X dev: enable CPython's "development mode", introducing additional runtimechecks which are too expensive to be enabled by default. Effect of thedeveloper mode:* Add default warning filter, as -W default* Install debug hooks on memory allocators: see the PyMem_SetupDebugHooks()C function* Enable the faulthandler module to dump the Python traceback on a crash* Enable asyncio debug mode* Set the dev_mode attribute of sys.flags to True* io.IOBase destructor logs close() exceptions-X utf8: enable UTF-8 mode for operating system interfaces, overriding the defaultlocale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it wouldotherwise activate automatically)-X pycache_prefix=PATH: enable writing .pyc files to a parallel tree rooted at thegiven directory instead of to the code tree-X warn_default_encoding: enable opt-in EncodingWarning for 'encoding=None' --check-hash-based-pycs always|default|never:control how Python invalidates hash-based .pyc files file : program read from script file - : program read from stdin (default; interactive mode if a tty) arg ...: arguments passed to program in sys.argv[1:]Other environment variables: PYTHONSTARTUP: file executed on interactive startup (no default) PYTHONPATH : ';'-separated list of directories prefixed to thedefault module search path. The result is sys.path. PYTHONHOME : alternate <prefix> directory (or <prefix>;<exec_prefix>).The default module search path uses <prefix>\python{major}{minor}. PYTHONPLATLIBDIR : override sys.platlibdir. PYTHONCASEOK : ignore case in 'import' statements (Windows). PYTHONUTF8: if set to 1, enable the UTF-8 mode. PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr. PYTHONFAULTHANDLER: dump the Python traceback on fatal errors. PYTHONHASHSEED: if this variable is set to 'random', a random value is usedto seed the hashes of str and bytes objects. It can also be set to aninteger in the range [0,4294967295] to get hash values with apredictable seed. PYTHONMALLOC: set the Python memory allocators and/or install debug hookson Python memory allocators. Use PYTHONMALLOC=debug to install debughooks. PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the localecoercion behavior. Use PYTHONCOERCECLOCALE=warn to request display oflocale coercion and locale compatibility warnings on stderr. PYTHONBREAKPOINT: if this variable is set to 0, it disables the defaultdebugger. It can be set to the callable of your debugger of choice. PYTHONDEVMODE: enable the development mode. PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files. PYTHONWARNDEFAULTENCODING: enable opt-in EncodingWarning for 'encoding=None'.
python help函数
help(request)
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking
help()
, it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters.This function is added to the built-in namespace by the
site
module.
进入帮助系统(简练的python文档系统)
>>> help()Welcome to Python 3.9's help utility!If this is your first time using Python, you should definitely check out the tutorial on the Internet at https://docs.python.org/3.9/tutorial/.Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit".To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords", "symbols", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as "spam", type "modules spam".help>
To get a list of available modules, keywords, symbols, or topics, type “modules”, “keywords”, “symbols”, or “topics”. Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as “spam”, type “modules spam”.
查阅内置模块(函数/异常/对象)
help("builtins")
通常传入字符串给
help()
函数更有可能查询成功例如
help(builtins)
会报错,但是help("builtins")
则可以正确工作或者进入帮助交互系统
help> builtins Help on built-in module builtins:NAMEbuiltins - Built-in functions, exceptions, and other objects.DESCRIPTIONNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.CLASSESobjectBaseExceptionExceptionArithmeticErrorFloatingPointErrorOverflowErrorZeroDivisionErrorAssertionErrorAttributeErrorBufferErrorEOFErrorImportErrorModuleNotFoundErrorLookupErrorIndexErrorKeyErrorMemoryErrorNameErrorUnboundLocalErrorOSErrorBlockingIOErrorChildProcessErrorConnectionErrorBrokenPipeErrorConnectionAbortedErrorConnectionRefusedErrorConnectionResetErrorFileExistsErrorFileNotFoundErrorInterruptedErrorIsADirectoryErrorNotADirectoryErrorPermissionErrorProcessLookupErrorTimeoutErrorReferenceErrorRuntimeErrorNotImplementedError .....sorted(iterable, /, *, key=None, reverse=False)Return a new list containing all items from the iterable in ascending order.A custom key function can be supplied to customize the sort order, and thereverse flag can be set to request the result in descending order.sum(iterable, /, start=0)Return the sum of a 'start' value (default: 0) plus an iterable of numbersWhen the iterable is empty, return the start value.This function is intended specifically for use with numeric values and mayreject non-numeric types.vars(...)vars([object]) -> dictionaryWithout arguments, equivalent to locals().With an argument, equivalent to object.__dict__.DATAEllipsis = EllipsisFalse = FalseNone = NoneNotImplemented = NotImplementedTrue = True__debug__ = Truecopyright = Copyright (c) 2001-2021 Python Software Foundati...ematisc...credits = Thanks to CWI, CNRI, BeOpen.com, Zope Corpor...opment. ...exit = Use exit() or Ctrl-Z plus Return to exithelp = Type help() for interactive help, or help(object) for help abou...license = See https://www.python.org/psf/license/quit = Use quit() or Ctrl-Z plus Return to exitFILE(built-in)
内置类型
help> TYPES The standard type hierarchy ***************************Below is a list of the types that are built into Python. ... ...Python distinguishes between integers, floating point numbers, andcomplex numbers:"numbers.Integral"These represent elements from the mathematical set of integers(positive and negative).There are two types of integers:Integers ("int")These represent numbers in an unlimited range, subject toavailable (virtual) memory only. For the purpose of shiftand mask operations, a binary representation is assumed, andnegative numbers are represented in a variant of 2Æscomplement which gives the illusion of an infinite string ofsign bits extending to the left.Booleans ("bool")These represent the truth values False and True. The twoobjects representing the values "False" and "True" are theonly Boolean objects. The Boolean type is a subtype of theinteger type, and Boolean values behave like the values 0 and1, respectively, in almost all contexts, the exception beingthat when converted to a string, the strings ""False"" or""True"" are returned, respectively.The rules for integer representation are intended to give themost meaningful interpretation of shift and mask operationsinvolving negative integers."numbers.Real" ("float")These represent machine-level double precision floating pointnumbers. You are at the mercy of the underlying machinearchitecture (and C or Java implementation) for the acceptedrange and handling of overflow. Python does not support single-precision floating point numbers; the savings in processor andmemory usage that are usually the reason for using these aredwarfed by the overhead of using objects in Python, so there isno reason to complicate the language with two kinds of floatingpoint numbers."numbers.Complex" ("complex")These represent complex numbers as a pair of machine-leveldouble precision floating point numbers. The same caveats applyas for floating point numbers. The real and imaginary parts of acomplex number "z" can be retrieved through the read-onlyattributes "z.real" and "z.imag". ....
区分大小写
例如
help> types #不同于 help> TYPES
help> typesHelp on module types:NAMEtypes - Define names for built-in types that aren't directly accessible as a builtin.MODULE REFERENCEhttps://docs.python.org/3.10/library/types.htmlThe following documentation is automatically generated from the Pythonsource files. It may be incomplete, incorrect or include features thatare considered implementation detail and may vary between Pythonimplementations. When in doubt, consult the module reference at thelocation listed above.CLASSESbuiltins.objectbuiltins.NoneTypebuiltins.NotImplementedType
help> TYPES The standard type hierarchy ***************************Below is a list of the types that are built into Python. ... ...
查看可用的帮助话题
help> topicsHere is a list of available topics. Enter any topic name to get more help.ASSERTION DELETION LOOPING SHIFTING ASSIGNMENT DICTIONARIES MAPPINGMETHODS SLICINGS ATTRIBUTEMETHODS DICTIONARYLITERALS MAPPINGS SPECIALATTRIBUTES ATTRIBUTES DYNAMICFEATURES METHODS SPECIALIDENTIFIERS AUGMENTEDASSIGNMENT ELLIPSIS MODULES SPECIALMETHODS BASICMETHODS EXCEPTIONS NAMESPACES STRINGMETHODS BINARY EXECUTION NONE STRINGS BITWISE EXPRESSIONS NUMBERMETHODS SUBSCRIPTS BOOLEAN FLOAT NUMBERS TRACEBACKS CALLABLEMETHODS FORMATTING OBJECTS TRUTHVALUE CALLS FRAMEOBJECTS OPERATORS TUPLELITERALS CLASSES FRAMES PACKAGES TUPLES CODEOBJECTS FUNCTIONS POWER TYPEOBJECTS COMPARISON IDENTIFIERS PRECEDENCE TYPES COMPLEX IMPORTING PRIVATENAMES UNARY CONDITIONAL INTEGER RETURNING UNICODE CONTEXTMANAGERS LISTLITERALS SCOPING CONVERSIONS LISTS SEQUENCEMETHODS DEBUGGING LITERALS SEQUENCES
可用的符号
help> symbolsHere is a list of the punctuation symbols which Python assigns special meaning to. Enter any symbol to get more help.!= + <= __ " += <> ` """ , == b" % - > b' %= -= >= f" & . >> f' &= ... >>= j ' / @ r" ''' // J r' ( //= [ u" ) /= \ u' * : ] | ** < ^ |= **= << ^= ~ *= <<= _
help> FUNCTIONS Functions *********Function objects are created by function definitions. The only operation on a function object is to call it: "func(argument-list)".There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types.See Function definitions for more information.Related help topics: def, TYPES
可用模块
help> modulesPlease wait a moment while I gather a list of all available modules...IPython brotli matplotlib_inline struct OpenSSL bs4 menuinst subprocess __future__ builtins mimetypes sunau _abc bz2 mistune symbol _aix_support cProfile mmap symtable _argon2_cffi_bindings calendar mmapfile sys _ast catalan mmsystem sysconfig _asyncio certifi modulefinder tabnanny _bisect cffi more_itertools tarfile .....
查看具体对象
>>> help(str) Help on class str in module builtins:class str(object)| str(object='') -> str| str(bytes_or_buffer[, encoding[, errors]]) -> str|| Create a new string object from the given object. If encoding or| errors is specified, then the object must expose a data buffer| that will be decoded using the given encoding and error handler.| Otherwise, returns the result of object.__str__() (if defined)| or repr(object).| encoding defaults to sys.getdefaultencoding().| errors defaults to 'strict'.|| Methods defined here:|| __add__(self, value, /)| Return self+value.|| __contains__(self, key, /)| Return key in self.|
查看指定对象函数的帮助
例如,字符串类型:str的startswith函数
help> str.startswith Help on method_descriptor in str:str.startswith = startswith(...)S.startswith(prefix[, start[, end]]) -> boolReturn True if S starts with the specified prefix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.prefix can also be a tuple of strings to try.
eval
eval(expression, globals=None, locals=None)
The arguments are a string and optional globals and locals.
If provided, globals must be a dictionary.
If provided, locals can be any mapping object.
The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.
- If the globals dictionary is present and does not contain a value for the key
__builtins__
, a reference to the dictionary of the built-in modulebuiltins
is inserted under that key before expression is parsed. - That way you can control what builtins are available to the executed code by inserting your own
__builtins__
dictionary into globals before passing it toeval()
. - If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where
eval()
is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.
- If the globals dictionary is present and does not contain a value for the key
The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
>>> x = 1 >>> eval('x+1') 2
This function can also be used to execute arbitrary code objects (such as those created by
compile()
). In this case, pass a code object instead of a string.If the code object has been compiled with
'exec'
as the mode argument,eval()
's return value will beNone
.Hints: dynamic execution of statements is supported by the
exec()
function. Theglobals()
andlocals()
functions return the current global and local dictionary, respectively, which may be useful to pass around for use byeval()
orexec()
.If the given source is a string, then leading and trailing spaces and tabs are stripped.
See
ast.literal_eval()
for a function that can safely evaluate strings with expressions containing only literals.Raises an auditing event
exec
with the code object as the argument. Code compilation events may also be raised.
repr
repr(object)
Return a string containing a printable representation of an object.
>>> type(repr("ab")) <class 'str'> >>> repr("abc") "'abc'" >>> str("abc") 'abc' >>> "abc" 'abc'
repr()和str()的返回结果都是字符串
有时两者的结果十分相近,甚至一样
>>> str(11.2) '11.2' >>> repr(11.2) '11.2'
有时则很不相同
取决于被计算的对象(类)是如何定义
__repr__
和__str__
的.
For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to
eval()
;import datetime today = datetime.datetime.now()# Prints readable format for date-time objectprint (type(today),str(today)) # prints the official format of date-time object print (repr(today)) er_today=eval(repr(today)) print(type(er_today),er_today) ## # Python program to demonstrate writing of __repr__ and # __str__ for user defined classes# A user defined class to represent Complex numbers class Complex:# Constructordef __init__(self, real, imag):self.real = realself.imag = imag# For call to repr(). Prints object's informationdef __repr__(self):return 'by __repr__
python@内置帮助系统的使用@eval@repr@str@内置函数源代码查看相关推荐
- 中国口内X射线系统行业市场供需与战略研究报告
出版商:贝哲斯咨询 获取报告样本: 企业竞争态势 该报告涉及的主要国际市场参与者有Danaher.Sirona Dental.Carestream.Gendex.Owandy Radiology.TP ...
- python学习笔记(装饰器、迭代器生成器、内置函数、软件目录开发规范)
装饰器 定义:本质是函数,(功能:装饰其他函数):就是为其他函数添加附加功能 模拟场景一,在现有的函数中增加某个功能.现有的做法是定义新函数,并且加入函数中.需要修改源代码. def logger() ...
- 华为鸿蒙内置,内置鸿蒙系统,华为生态产品海雀智能摄像头Pro体验
提起华为鸿蒙系统,估计很多人都不陌生,作为一款分布式操作系统,目前已经在华为智慧屏.华为手表.九阳.美的等产品中内置了鸿蒙系统,手机鸿蒙系统目前正在内测,估计很快大多数华为荣耀手机都可以升级鸿蒙系统了 ...
- 查看python内部模块命令,内置函数,查看python已经安装的模块命令
查看python内部模块命令,内置函数,查看python已经安装的模块命令 可以用dir(modules) 或者用 pip list 或者用 help('modules') 或者用 python -m ...
- w10系统自带linux系统,win10下,内置linux系统的安装和体验,你造吗?
原标题:win10下,内置linux系统的安装和体验,你造吗? 众所周知,windows系统和linux系统一直是水火不容,而在最新的win10系统却完美兼容了linux系统,但是在默认情况下是关闭的 ...
- python中表达式4**0.5的值为_Python内置函数__用来返回序列中的最小元素
[填空题]表达式 int(4**0.5) 的值为 [判断题]3+4j不是合法的Python表达式. [填空题]已知列表对象x = ['11', '2', '3'],则表达式 max(x) 的值为 [填 ...
- python 3.28 第三章 函数嵌套/名称空间//内置名称空间/全局名称空间/局部名称空间/作用域/函数对象/闭包函数。...
1 函数嵌套: 函数内可以调用了其他的函数. # def max2(x,y):# if x > y:# return x# else:# return y## def max3(x,y,z):# ...
- python中str函数用法_python中str内置函数用法总结
大家在使用python的过程中,应该在敲代码的时候经常遇到str内置函数,为了防止大家搞混,本文整理归纳了str内置函数.1字符串查找类:find.index:2.字符串判断类:islower.isa ...
- 鸿蒙系统摄像头,内置鸿蒙系统,华为生态产品海雀智能摄像头Pro体验
提起华为鸿蒙系统,估计很多人都不陌生,作为一款分布式操作系统,目前已经在华为智慧屏.华为手表.九阳.美的等产品中内置了鸿蒙系统,手机鸿蒙系统目前正在内测,估计很快大多数华为荣耀手机都可以升级鸿蒙系统了 ...
最新文章
- 允许活动内容如脚本和activex控件
- mysql 执行计划 优化_执行计划
- 代码管理 ,git 命令整理
- 一个web项目在myeclipse中add deployment时无法被识别出来的原因
- ios13看怎么airpods电量_你的iPhone升级iOS13了吗?iOS13升级前,必知的七大新功能...
- Separate texture from black background
- .Net软件设计新思维
- Android Service 播放音乐
- python elasticsearch dsl_python 查询 elasticsearch 常用方法(Query DSL)
- cron表达式每一个小时_嵊泗新闻网丨两千小时的热爱——任春华:用志愿服务守护每一个笑容...
- 如何删除目录下的页码,使文章页码从正文开始
- linux tar压缩解压缩文件夹、文件命令详解
- 问题 K: [入门OJ]开会时间(初中生请多多指教)
- 准备情人节礼物比写代码难?来看看IT直男给女友们的礼物
- Android webview加载天猫店铺时会报net::ERR_UNKNOWN_URL_SCHEME;
- python随手记自动记账_随手记 怎么实现自动记账
- The following tasks did not complete: first,Did you forget to signal async completion?问题
- Glide系列(四) — Glide缓存流程分析
- 31次课(iptables filter表案例、iptables nat表应用)
- 学生信息管理系统用php,PHP案例:学生信息管理系统
热门文章
- 数据结构(九)——外部排序之外排序
- ACM四五周学习总结
- 子查询和关联查询 效率
- mac 备份树莓派镜像
- 面向对象基础任务训练分享
- 我国计算机在办公应用普及时间,论如何提高水利工程中计算机的应用
- 12. Vuepress2.x 隐藏指定页的 sidebar
- php链接mysql 老是die_php连接MySQL时, 为什么die(错误信息: . $conn-connect_error) 不返回错误信息?...
- linux系统查看日历
- 【目标检测评价指标】
- 中国口内X射线系统行业市场供需与战略研究报告