在 Python 中,有大量的内置模块,模块中的定义(例如:变量、函数、类)众多,不可能全部都记住,这时 dir()
dir()
是一个内置函数,用于列出对象的所有属性及方法。在 Python 中,一切皆对象,模块也不例外,所以模块也可以使用 dir()
。除了常用定义外,其它的不需要全部记住它,交给 dir()
- 简述
- dir
- 使用 dir
- 自定义对象
版权所有:一去丶二三里,转载请注明出处:
dir()
如果对 dir()
的用法不是很清楚,可以使用 help()
>>> help(dir)
Help on built-in function dir in module builtins:
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.
(END)
基本场景:
- 如果
dir()
- 如果对象提供了
__dir__()
- 方法,则它将会被使用;否则,使用默认的
dir()
使用 dir()
使用 dir()
>>> import math # 内置模块 math
>>> dir(math)
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
其中,以下划线(_
)开头的名称并不是自己定义的,而是与模块相关的默认属性。例如,属性 __name__
>>> math.__name__
'math'
如果没有参数,dir()
>>> s = 'Hello'
>>> l = [1, 2, 3]
>>> abs = math.fabs
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'l', 'math', 's']
通过导入 builtins
>>> import builtins
>>> 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', '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', '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']
自定义对象
根据 help 中的描述,可以看到:
If the object supplies a method named __dir__, it will be used;
也就是说,如果对象有 __dir__()
>>> class Person:
... def __dir__(self):
... return ['name', 'sex', 'age']
...
>>> p = Person()
>>> dir(p)
['age', 'name', 'sex']
-------------------------------------
abs(number) | 返回一个数的绝对值 |
apply(function[, args[, kwds]]) | 调用给定函数,可选择提供参数 |
all(iterable) | 如果所有iterable的元素均为真则返回True, 否则返回False |
any(iterable) | 如果有任一iterable的元素为真则返回True,否则返回False |
basestring() | str和unicode抽象超类,用于检查类型 |
bool(object) | 返回True或False,取决于Object的布尔值 |
callable(object) | 检查对象是否可调用 |
chr(number) | 返回ASCII码为给定数字的字符 |
classmethod(func) | 通过一个实例方法创建类的方法 |
cmp(x, y) | 比较x和y——如果xy则返回证书;如果x==y,返回0 |
complex(real[, imag]) | 返回给定实部(以及可选的虚部)的复数 |
delattr(object, name) | 从给定的对象中删除给定的属性 |
dict([mapping-or-sequence]) | 构造一个字典,可选择从映射或(键、值)对组成的列表构造。 也可以使用关键字参数调用。 |
dir([object]) | 当前可见作用于域的(大多数)名称的列表, 或者是选择性地列出给定对象的(大多数)特性 |
divmod(a, b) | 返回(a//b, a%b)(float类型有特殊规则) |
enumerate(iterable) | 对iterable中的所有项迭代(索引,项目)对 |
eval(string[, globals[, locals]]) | 对包含表达式的字符串进行计算。 可选择在给定的全局作用域或者局部作用域中进行 |
execfile(file[, globals[, locals]]) | 执行一个python文件, 可选在给定全局作用域或者局部作用域中进行 |
file(filename[, mode[, bufsize]]) | 创建给定文件名的文件, 可选择使用给定的模式和缓冲区大小 |
filter(function, sequence) | 返回给定序列中函数返回值的元素的列表 |
float(object) | 将字符串或者数值转换为float类型 |
frozenset([iterable]) | 创建一个不可变集合,这意味着不能将添加到其它集合中 |
getattr(object, name[, default]) | 返回给定对象中所指定的特性的值,可选择给定默认值 |
globals() | 返回表示当前作用域的字典 |
hasattr(object, name) | 检查给定的对象是否有指定的属性 |
help([object]) | 调用内建的帮助系统,或者打印给定对象的帮助信息 |
id(number) | 返回给定对象的唯一ID |
input([prompt]) | 等同于eval(raw_input(prompt) |
int(object[, radix]) | 将字符串或者数字(可以提供基数)转换为整数 |
isinstance(object, classinfo) | 检查给定的对象object是否是给定的classinfo值的实例, classinfo可以是类对象、类型对象或者类对象和类型对象的元组 |
issubclass(class1, class2) | 检查class1是否是class2的子类(每个类都是自身的子类) |
iter(object[, sentinel]) | 返回一个迭代器对象,可以是用于迭代序列的objectiter()迭代器 (如果object支持_getitem方法的话),或者提供一个sentinel, 迭代器会在每次迭代中调用object,直到返回sentinel |
len(object) | 返回给定对象的长度(项的个数) |
list([sequence]) | 构造一个列表,可选择使用与所提供序列squence相同的项 |
locals() | 返回表示当前局部作用域的字典(不要修改这个字典) |
long(object[, radix]) | 将字符串(可选择使用给定的基数radix)或者数字转化为长整型 |
map(function, sequence, ...) | 创建由给定函数function应用到所提供列表sequence每个项目时返回的值组成的列表 |
max(object1, [object2, ...]) | 如果object1是非空序列,那么就返回最大的元素。 否则返回所提供参数(object1,object2...)的最大值 |
min(object1, [object2, ...]) | 如果object1是非空序列,那么就返回最小的元素。 否则返回所提供参数(object1,object2...)的最小值 |
object() | 返回所有新式类的技术Object的实例 |
oct(number) | 将整型数转换为八进制表示的字符串 |
open(filename[, mode[, bufsize]]) | file的别名(在打开文件的时候使用open而不是file |
ord(char) | 返回给定单字符(长度为1的字符串或者Unicode字符串)的ASCII值 |
pow(x, y[, z]) | 返回x的y次方,可选择模除z |
property([fget[, fset[, fdel[, doc]]]]) | 通过一组访问器创建属性 |
range([start, ]stop[, step]) | 使用给定的起始值(包括起始值,默认为0)和结束值(不包括) 以及步长(默认为1)返回数值范围(以列表形式) |
raw_input([prompt]) | 将用户输入的数据作为字符串返回,可选择使用给定的提示符prompt |
reduce(function, sequence[, initializer]) | 对序列的所有渐增地应用于给定的函数, 使用累积的结果作为第一个参数, 所有的项作为第二个参数,可选择给定的起始值(initializer) |
reload(module) | 重载入一个已经载入的模块并将其返回 |
repr(object) | 返回表示对象的字符串,一般作为eval的参数使用 |
reversed(sequence) | 返回序列的反向迭代器 |
round(float[, n]) | 将给定的浮点数四舍五入,小数点后保留n位(默认为0) |
set([iterable) | 返回从iterable(如果给出)生成的元素集合 |
setattr(object, name, value) | 设定给定对象的指定属性的值为给定的值 |
sorted(iterable[, cmp][,key][, reverse]) | 从iterable的项目中返回一个新的排序后的列表。 可选的参数和列表方法与sort中的相同 |
staticmethod(func) | 从一个实例方法创建静态(类)方法 |
str(object) | 返回表示给定对象object的格式化好的字符串 |
sum(seq[, start]) | 返回添加到可选参数start(默认为0)中的一系列数字的和 |
super(type[, obj/type) | 返回给定类型(可选为实例化的)的超类 |
tuple([sequence]) | 构造一个元祖,可选择使用同提供的序列sequence一样的项 |
type(object) | 返回给定对象的类型 |
type(name, base, dict) | 使用给定的名称、基类和作用域返回一个新的类型对象 |
unichr(number) | chr的Unicode版本 |
unicode(object[, encoding[, errors]]) | 返回给定对象的Unicode编码版本,可以给定编码方式和处理错误的模式 ('strict'、'replace'或者'ignore','strict'为默认模式) |
vars([object]) | 返回表示局部作用域的字典,或者对应给定对象特性的字典 |
xrange([start, ]stop[, step]) | 类似于range,但是返回的对象使用内存较少,而且只用于迭代 |
zip(sequence1, ...) | 返回元组的列表,每个元组包括一个给定序列中的项。 返回的列表的长度和所提供的序列的最短长度相同 |
--------------------------------
http://docspy3zh.readthedocs.io/en/latest/library/functions.html
-----------------
Python 3.7.0b2 (v3.7.0b2:b0ef5c979b, Feb 28 2018, 02:24:20) [MSC v.1912 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
>>> 3<<2
12
>>> 3>>2
0
>>> 3&7
3
>>> 3|8
11
>>> a={2,3,5};b={4,3,2}
>>> a
{2, 3, 5}
>>> b
{2, 3, 4}
>>> a;b
{2, 3, 5}
{2, 3, 4}
>>> a|b
{2, 3, 4, 5}
>>> a&b
{2, 3}
>>> a^b
{4, 5}
>>> a-b
{5}
>>> a*3
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
a*3
TypeError: unsupported operand type(s) for *: 'set' and 'int'
>>>
>>> a
{2, 3, 5}
>>> 3 is in a
SyntaxError: invalid syntax
>>> 3 in a
True
>>> 3 not in a
False
>>> 1 and 4
4
>>> 1>3 and 4<4
False
>>> 1<3 and 3
3
>>> 1>3 and 3
False
>>> import numpy
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
import numpy
ModuleNotFoundError: No module named 'numpy'
>>>
>>>
>>> import numpy
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
import numpy
ModuleNotFoundError: No module named 'numpy'
>>> 2--
SyntaxError: invalid syntax
>>> 2++
SyntaxError: invalid syntax
>>> --2
2
>>> -+2
-2
>>> +-2
-2
>>> 2-+3
-1
>>> 0b1
1
>>> c=0b2
SyntaxError: invalid token
>>> 0b2
SyntaxError: invalid token
>>> c=0b10
>>> c
2
>>> 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', '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']
>>>
>>>
>>> help(abs)
Help on built-in function abs in module builtins:
abs(x, /)
Return the absolute value of the argument.
>>> abs()
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
abs()
TypeError: abs() takes exactly one argument (0 given)
>>> abs(3)
3
>>> abs(3,/)
SyntaxError: invalid syntax
>>> abs(3,1)
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
abs(3,1)
TypeError: abs() takes exactly one argument (2 given)
>>> help(bin)
Help on built-in function bin in module builtins:
bin(number, /)
Return the binary representation of an integer.
>>> bin(2796202)
'0b1010101010101010101010'
>>> sqrt()
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
sqrt()
NameError: name 'sqrt' is not defined
>>> range(12)
range(0, 12)
>>> help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return an object that produces a sequence of integers from start (inclusive)
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
| start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
| These are exactly the valid indices for a list of 4 elements.
| When step is given, it specifies the increment (or decrement).
|
| Methods defined here:
|
| __bool__(self, /)
| self != 0
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(...)
| Return a reverse iterator.
|
| count(...)
| rangeobject.count(value) -> integer -- return number of occurrences of value
|
| index(...)
| rangeobject.index(value, [start, [stop]]) -> integer -- return index of value.
| Raise ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| start
|
| step
|
| stop
>>>
>>> help(all)
Help on built-in function all in module builtins:
all(iterable, /)
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
>>> all(a)
True
>>> a
{2, 3, 5}
>>> a.append('3')
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
a.append('3')
AttributeError: 'set' object has no attribute 'append'
>>> a |{'a'}
{2, 3, 5, 'a'}
>>> b=_
>>> b
{2, 3, 5, 'a'}
>>> all(b)
True
>>> any(b)
True
>>> help(bool)
Help on class bool in module builtins:
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
|
| Method resolution order:
| bool
| int
| object
|
| Methods defined here:
|
| __and__(self, value, /)
| Return self&value.
|
| __or__(self, value, /)
| Return self|value.
|
| __rand__(self, value, /)
| Return value&self.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __str__(self, /)
| Return str(self).
|
| __xor__(self, value, /)
| Return self^value.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from int:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __bool__(self, /)
| self != 0
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Default object formatter.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __round__(...)
| Rounding an Integral returns itself.
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| to_bytes(self, /, length, byteorder, *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods inherited from int:
|
| from_bytes(bytes, byteorder, *, signed=False) from builtins.type
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from int:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
>>> 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.stdout.
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.
>>>
>>>
>>> bin(555)
'0b1000101011'
>>> oct(33)
'0o41'
>>> hex(123)
'0x7b'
>>> int(-3.2)
-3
>>> help(int)
Help on class int in module builtins:
class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by '+' or '-' and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int('0b100', base=0)
| 4
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
|
| __add__(self, value, /)
| Return self+value.
|
| __and__(self, value, /)
| Return self&value.
|
| __bool__(self, /)
| self != 0
|
| __ceil__(...)
| Ceiling of an Integral returns itself.
|
| __divmod__(self, value, /)
| Return divmod(self, value).
|
| __eq__(self, value, /)
| Return self==value.
|
| __float__(self, /)
| float(self)
|
| __floor__(...)
| Flooring an Integral returns itself.
|
| __floordiv__(self, value, /)
| Return self//value.
|
| __format__(self, format_spec, /)
| Default object formatter.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __index__(self, /)
| Return self converted to an integer, if self is suitable for use as an index into a list.
|
| __int__(self, /)
| int(self)
|
| __invert__(self, /)
| ~self
|
| __le__(self, value, /)
| Return self<=value.
|
| __lshift__(self, value, /)
| Return self<<value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __neg__(self, /)
| -self
|
| __or__(self, value, /)
| Return self|value.
|
| __pos__(self, /)
| +self
|
| __pow__(self, value, mod=None, /)
| Return pow(self, value, mod).
|
| __radd__(self, value, /)
| Return value+self.
|
| __rand__(self, value, /)
| Return value&self.
|
| __rdivmod__(self, value, /)
| Return divmod(value, self).
|
| __repr__(self, /)
| Return repr(self).
|
| __rfloordiv__(self, value, /)
| Return value//self.
|
| __rlshift__(self, value, /)
| Return value<<self.
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __ror__(self, value, /)
| Return value|self.
|
| __round__(...)
| Rounding an Integral returns itself.
| Rounding with an ndigits argument also returns an integer.
|
| __rpow__(self, value, mod=None, /)
| Return pow(value, self, mod).
|
| __rrshift__(self, value, /)
| Return value>>self.
|
| __rshift__(self, value, /)
| Return self>>value.
|
| __rsub__(self, value, /)
| Return value-self.
|
| __rtruediv__(self, value, /)
| Return value/self.
|
| __rxor__(self, value, /)
| Return value^self.
|
| __sizeof__(self, /)
| Returns size in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| __sub__(self, value, /)
| Return self-value.
|
| __truediv__(self, value, /)
| Return self/value.
|
| __trunc__(...)
| Truncating an Integral returns itself.
|
| __xor__(self, value, /)
| Return self^value.
|
| bit_length(self, /)
| Number of bits necessary to represent self in binary.
|
| >>> bin(37)
| '0b100101'
| >>> (37).bit_length()
| 6
|
| conjugate(...)
| Returns self, the complex conjugate of any int.
|
| to_bytes(self, /, length, byteorder, *, signed=False)
| Return an array of bytes representing an integer.
|
| length
| Length of bytes object to use. An OverflowError is raised if the
| integer is not representable with the given number of bytes.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Determines whether two's complement is used to represent the integer.
| If signed is False and a negative integer is given, an OverflowError
| is raised.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_bytes(bytes, byteorder, *, signed=False) from builtins.type
| Return the integer represented by the given array of bytes.
|
| bytes
| Holds the array of bytes to convert. The argument must either
| support the buffer protocol or be an iterable object producing bytes.
| Bytes and bytearray are examples of built-in objects that support the
| buffer protocol.
| byteorder
| The byte order used to represent the integer. If byteorder is 'big',
| the most significant byte is at the beginning of the byte array. If
| byteorder is 'little', the most significant byte is at the end of the
| byte array. To request the native byte order of the host system, use
| `sys.byteorder' as the byte order value.
| signed
| Indicates whether two's complement is used to represent the integer.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| denominator
| the denominator of a rational number in lowest terms
|
| imag
| the imaginary part of a complex number
|
| numerator
| the numerator of a rational number in lowest terms
|
| real
| the real part of a complex number
>>> int('0x22b')
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
int('0x22b')
ValueError: invalid literal for int() with base 10: '0x22b'
>>> int('0x22b',16)
555
>>> int(bin(54321),2)
54321
>>> inf
Traceback (most recent call last):
File "<pyshell#72>", line 1, in <module>
inf
NameError: name 'inf' is not defined
>>> float('inf')
inf
>>> nan=floa('inf')
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
nan=floa('inf')
NameError: name 'floa' is not defined
>>> float('inf')
inf
>>> complex('inf')
(inf+0j)
>>> ord('a')
97
>>> ord('sfd')
Traceback (most recent call last):
File "<pyshell#78>", line 1, in <module>
ord('sfd')
TypeError: ord() expected a character, but string of length 3 found
>>> chr(ord('d')+1)
'e'
>>> chr(ord('东')+1)
'丝'
>>> ord('d')
100
>>> str([34,4])
'[34, 4]'
>>>
>>> ascii('s')
"'s'"
>>> help(bytes)
Help on class bytes in module builtins:
class bytes(object)
| bytes(iterable_of_ints) -> bytes
| bytes(string, encoding[, errors]) -> bytes
| bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
| bytes(int) -> bytes object of size given by the parameter initialized with null bytes
| bytes() -> empty bytes object
|
| Construct an immutable array of bytes from:
| - an iterable yielding integers in range(256)
| - a text string encoded using the specified encoding
| - any object implementing the buffer API.
| - an integer
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.n
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return self*value.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(...)
| B.capitalize() -> copy of B
|
| Return a copy of B with only its first character capitalized (ASCII)
| and the rest lower-cased.
|
| center(...)
| B.center(width[, fillchar]) -> copy of B
|
| Return B centered in a string of length width. Padding is
| done using the specified fill character (default is a space).
|
| count(...)
| B.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of subsection sub in
| bytes B[start:end]. Optional arguments start and end are interpreted
| as in slice notation.
|
| decode(self, /, encoding='utf-8', errors='strict')
| Decode the bytes using the codec registered for encoding.
|
| encoding
| The encoding with which to decode the bytes.
| errors
| The error handling scheme to use for the handling of decoding errors.
| The default is 'strict' meaning that decoding errors raise a
| UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
| as well as any other name registered with codecs.register_error that
| can handle UnicodeDecodeErrors.
|
| endswith(...)
| B.endswith(suffix[, start[, end]]) -> bool
|
| Return True if B ends with the specified suffix, False otherwise.
| With optional start, test B beginning at that position.
| With optional end, stop comparing B at that position.
| suffix can also be a tuple of bytes to try.
|
| expandtabs(...)
| B.expandtabs(tabsize=8) -> copy of B
|
| Return a copy of B where all tab characters are expanded using spaces.
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| B.find(sub[, start[, end]]) -> int
|
| Return the lowest index in B where subsection sub is found,
| such that sub is contained within B[start,end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| hex(...)
| B.hex() -> string
|
| Create a string of hexadecimal numbers from a bytes object.
| Example: b'\xb9\x01\xef'.hex() -> 'b901ef'.
|
| index(...)
| B.index(sub[, start[, end]]) -> int
|
| Return the lowest index in B where subsection sub is found,
| such that sub is contained within B[start,end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the subsection is not found.
|
| isalnum(...)
| B.isalnum() -> bool
|
| Return True if all characters in B are alphanumeric
| and there is at least one character in B, False otherwise.
|
| isalpha(...)
| B.isalpha() -> bool
|
| Return True if all characters in B are alphabetic
| and there is at least one character in B, False otherwise.
|
| isascii(...)
| B.isascii() -> bool
|
| Return True if B is empty or all characters in B are ASCII,
| False otherwise.
|
| isdigit(...)
| B.isdigit() -> bool
|
| Return True if all characters in B are digits
| and there is at least one character in B, False otherwise.
|
| islower(...)
| B.islower() -> bool
|
| Return True if all cased characters in B are lowercase and there is
| at least one cased character in B, False otherwise.
|
| isspace(...)
| B.isspace() -> bool
|
| Return True if all characters in B are whitespace
| and there is at least one character in B, False otherwise.
|
| istitle(...)
| B.istitle() -> bool
|
| Return True if B is a titlecased string and there is at least one
| character in B, i.e. uppercase characters may only follow uncased
| characters and lowercase characters only cased ones. Return False
| otherwise.
|
| isupper(...)
| B.isupper() -> bool
|
| Return True if all cased characters in B are uppercase and there is
| at least one cased character in B, False otherwise.
|
| join(self, iterable_of_bytes, /)
| Concatenate any number of bytes objects.
|
| The bytes whose method is called is inserted in between each pair.
|
| The result is returned as a new bytes object.
|
| Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.
|
| ljust(...)
| B.ljust(width[, fillchar]) -> copy of B
|
| Return B left justified in a string of length width. Padding is
| done using the specified fill character (default is a space).
|
| lower(...)
| B.lower() -> copy of B
|
| Return a copy of B with all ASCII characters converted to lowercase.
|
| lstrip(self, bytes=None, /)
| Strip leading bytes contained in the argument.
|
| If the argument is omitted or None, strip leading ASCII whitespace.
|
| partition(self, sep, /)
| Partition the bytes into three parts using the given separator.
|
| This will search for the separator sep in the bytes. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original bytes
| object and two empty bytes objects.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| B.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in B where subsection sub is found,
| such that sub is contained within B[start,end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| B.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in B where subsection sub is found,
| such that sub is contained within B[start,end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raise ValueError when the subsection is not found.
|
| rjust(...)
| B.rjust(width[, fillchar]) -> copy of B
|
| Return B right justified in a string of length width. Padding is
| done using the specified fill character (default is a space)
|
| rpartition(self, sep, /)
| Partition the bytes into three parts using the given separator.
|
| This will search for the separator sep in the bytes, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty bytes
| objects and the original bytes object.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the sections in the bytes, using sep as the delimiter.
|
| sep
| The delimiter according which to split the bytes.
| None (the default value) means split on ASCII whitespace characters
| (space, tab, return, newline, formfeed, vertical tab).
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| Splitting is done starting at the end of the bytes and working to the front.
|
| rstrip(self, bytes=None, /)
| Strip trailing bytes contained in the argument.
|
| If the argument is omitted or None, strip trailing ASCII whitespace.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the sections in the bytes, using sep as the delimiter.
|
| sep
| The delimiter according which to split the bytes.
| None (the default value) means split on ASCII whitespace characters
| (space, tab, return, newline, formfeed, vertical tab).
| maxsplit
| Maximum number of splits to do.
| -1 (the default value) means no limit.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the bytes, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| B.startswith(prefix[, start[, end]]) -> bool
|
| Return True if B starts with the specified prefix, False otherwise.
| With optional start, test B beginning at that position.
| With optional end, stop comparing B at that position.
| prefix can also be a tuple of bytes to try.
|
| strip(self, bytes=None, /)
| Strip leading and trailing bytes contained in the argument.
|
| If the argument is omitted or None, strip leading and trailing ASCII whitespace.
|
| swapcase(...)
| B.swapcase() -> copy of B
|
| Return a copy of B with uppercase ASCII characters converted
| to lowercase ASCII and vice versa.
|
| title(...)
| B.title() -> copy of B
|
| Return a titlecased version of B, i.e. ASCII words start with uppercase
| characters, all remaining cased characters have lowercase.
|
| translate(self, table, /, delete=b'')
| Return a copy with each character mapped by the given translation table.
|
| table
| Translation table, which must be a bytes object of length 256.
|
| All characters occurring in the optional argument delete are removed.
| The remaining characters are mapped through the given translation table.
|
| upper(...)
| B.upper() -> copy of B
|
| Return a copy of B with all ASCII characters converted to uppercase.
|
| zfill(...)
| B.zfill(width) -> copy of B
|
| Pad a numeric string B with zeros on the left, to fill a field
| of the specified width. B is never truncated.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| fromhex(string, /) from builtins.type
| Create a bytes object from a string of hexadecimal numbers.
|
| Spaces between two numbers are accepted.
| Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| maketrans(frm, to, /)
| Return a translation table useable for the bytes or bytearray translate method.
|
| The returned table will be one where each byte in frm is mapped to the byte at
| the same position in to.
|
| The bytes objects frm and to must be of the same length.
>>>
>>>
>>>
>>> bytes(3)
b'\x00\x00\x00'
>>> bytes(4,'utf-8')
Traceback (most recent call last):
File "<pyshell#90>", line 1, in <module>
bytes(4,'utf-8')
TypeError: encoding without a string argument
>>> bytes('asdfd')
Traceback (most recent call last):
File "<pyshell#91>", line 1, in <module>
bytes('asdfd')
TypeError: string argument without an encoding
>>> bytes('asf','utf-8')
b'asf'
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> tuple(_)
(0, 1, 2, 3, 4)
>>> dict(zip('123','adc'))
{'1': 'a', '2': 'd', '3': 'c'}
>>> set('122334555')
{'5', '3', '2', '4', '1'}
>>> _.add(6)
>>> _
{'5', 6, '3', '2', '4', '1'}
>>> type([3])
<class 'list'>
>>> isinstance(3,int)
True
>>> isinstance(3j,(int,float,complex))
True
>>> help(max)
Help on built-in function max in module builtins:
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
>>> max(['2','111'])
'2'
>>> max(['2','34'],key=len)
'34'
>>> help(min)
Help on built-in function min in module builtins:
min(...)
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
>>> lst=[[randint(1,50) for i in range (5)]] for j in range(30)]
SyntaxError: invalid syntax
>>> help(sum)
Help on built-in function sum in module builtins:
sum(iterable, start=0, /)
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
>>> sum([2,34],2)
38
>>> sum([2,34],start=2)
Traceback (most recent call last):
File "<pyshell#110>", line 1, in <module>
sum([2,34],start=2)
TypeError: sum() takes no keyword arguments
>>> a='123'
>>> int(a)
123
>>> type(_)
<class 'int'>
>>> eval(a)
123
>>> type(_)
<class 'int'>
>>>
x
Traceback (most recent call last):
File "<pyshell#116>", line 2, in <module>
x
NameError: name 'x' is not defined
>>>
>>> x=input('please input: ')
please input: 23
>>> xx
Traceback (most recent call last):
File "<pyshell#119>", line 1, in <module>
xx
NameError: name 'xx' is not defined
>>> x
'23'
>>> type(x)
<class 'str'>
>>> int(x)
23
>>> eval(x)
23
>>> x=input()
[1,2,3]
>>> x
'[1,2,3]'
>>> int(x)
Traceback (most recent call last):
File "<pyshell#126>", line 1, in <module>
int(x)
ValueError: invalid literal for int() with base 10: '[1,2,3]'
>>> eval(x)
[1, 2, 3]
>>> x=input()
"'hello,word'"
>>> eval(x)
"'hello,word'"
>>> x=input()
qwddfg
>>> x
'qwddfg'
>>>