VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • Python入门技巧

1.6 Python入门技巧

以下介绍了一些比较实用的Python学习技巧,可以让初学者快速上手。

1.6.1 help函数

help用于启动Python内置的帮助系统(此函数主要在交互式中使用)。一般用在交互模式中。用来在控制台上打印某个模块、函数、类、方法、关键字等的帮助信息。
示例:
>>> help(print)
Help on built-in function print in module builtins:

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

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.out.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
练习
用help函数查看一下之前遇到的所有函数并熟悉。

1.6.2 dir函数

不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。
示例:
>>> dir(input)
['call', 'class', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'name', 'ne', 'new', 'qualname', 'reduce', 'reduce_ex', 'repr', 'self', 'setattr', 'sizeof', 'str', 'subclasshook', 'text_signature']
练习
用dir函数查看一下之前遇到的所有函数并熟悉。

1.6.3 id函数

每个对象在内存中都有一个地址,这个地址就是对象的标示。通过id函数可以返回对象的内存地址。这个函数可以用来判断对象是惟一的。
示例:
>>> id(3)
140574872
练习
创建几个变量,然后用id函数查看其内存地址。

1.6.4 __builtins__模块

Python在运行时会自动加载一些比较常用的变量、函数,无需用户手动导入。这些默认运行自动加载变量、函数等,都包含在__builtins__模块内,可以通过dir进行查看。
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', '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', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', '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']
上面的内容比较多,各种类型都有,看的不是很清楚,我们可以通过以下代码进行归类展示:


 
builtins = dir(__builtins__)
 
dct = {}
 
for _ in builtins:
 
if (tp := str(type(eval(_)))[8:-2]) in dct:
 
dct[tp].append(_)
 
else:
 
dct[tp] = [_]
 
for d, v in dct.items():
 
print(f"`{d}`:{v}")

输出的结果如下:



练习
创建一个新的脚本并尝试将上面的代码手动输入进去,然后运行查看结果。


相关教程