python 第二天
阿新 • • 發佈:2019-01-14
在 Python 中,有大量的內建模組,模組中的定義(例如:變數、函式、類)眾多,不可能全部都記住,這時 dir()
函式就非常有用了。
dir()
是一個內建函式,用於列出物件的所有屬性及方法。在 Python 中,一切皆物件,模組也不例外,所以模組也可以使用 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)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
基本場景:
- 如果
dir()
沒有引數,則返回當前作用域中的名稱列表;否則,返回給定 object 的一個已排序的屬性名稱列表。 - 如果物件提供了
__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']
- 1
- 2
- 3
其中,以下劃線(_
)開頭的名稱並不是自己定義的,而是與模組相關的預設屬性。
例如,屬性 __name__
表示模組名稱:
>>> math.__name__
'math'
- 1
- 2
如果沒有引數,dir()
會列出當前作用域中的名稱:
>>> s = 'Hello'
>>> l = [1, 2, 3]
>>> abs = math.fabs
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'l', 'math', 's']
- 1
- 2
- 3
- 4
- 5
通過匯入 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']
- 1
- 2
- 3
自定義物件
根據 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.
|