2.
Python
-
all(iterable) iterable ( iterable )
True:def all(iterable): for element in iterable: if not element: return False return True
-
any(iterable) iterable
TrueiterableFalse:def any(iterable): for element in iterable: if element: return True return False
-
bin(x) "0b" 2 Python
>>> bin(3) '0b11' >>> bin(-10) '-0b1010'
"0b"
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110')
-
class
bool([x]) TrueFalsex xFalseTrueboolint( int, float, complex )FalseTrue( )
-
class
bytearray([source[, encoding[, errors]]]) bytearray0 <= x < 256bytessee bytes bytearray )source :
- encoding ( errors)
bytearray()str.encode() - null
-
0 <= x < 256
0
- encoding ( errors)
-
callable(object) object
TrueFalseobject ()__call__()3.2 : Python 3.0 Python 3.2
-
chr(i) Unicode i
chr(97)'a'chr(8364)''ord()0 1,114,111 (16 0x10FFFF) i
ValueError
-
@classmethod -
:
class C: @classmethod def f(cls, arg1, arg2, ...): ...
@classmethod(decorator)(
C.f()) (C().f())C++ Java
staticmethod()
-
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) source AST
exec()eval()source AST AST ASTastfilename ; (
'<string>')mode ; source
'exec''eval''single'(None)The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling
compile(). If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it the future statements in effect around the call to compile are ignored.future OR
__future___Featurecompiler_flagoptimize ;
-1-O0(__debug__)1(assert__debug__)2(docstring )Python AST
ast.parse()'single''eval'codeIt is possible to crash the Python interpreter with a sufficiently large/complex string when compiling to an AST object due to stack depth limitations in Pythons AST compiler.
3.2 : Windows Mac
'exec'optimize3.5 : source
TypeError
-
class
complex([real[, imag]]) real + imag*1j () imag
intfloat0j+-complex('1+2j')complex('1 + 2j')ValueError3.6 :
-
delattr(object, name) setattr()delattr(x, 'foobar')del x.foobar
-
class
dict(**kwarg) -
class
dict(mapping, **kwarg) -
class
dict(iterable, **kwarg)
-
dir([object]) -
__dir__()__getattr__()__getattribute__()dir()__dir__()__dict____getattr__()dir()::
>>> import struct >>> dir() # show the names in the module namespace ['__builtins__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Shape: ... def __dir__(self): ... return ['area', 'perimeter', 'location'] >>> s = Shape() >>> dir(s) ['area', 'location', 'perimeter']
-
divmod(a, b) 2 ()
(a // b, a % b)(q, a % b)qmath.floor(a / b)1q * b + a % baa % bb0 <= abs(a % b) < abs(b)
-
enumerate(iterable, start=0) enumerate iterable iterator
enumerate()__next__()( 0 start ) iterable>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
:
def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1
-
eval(expression, globals=None, locals=None) globalslocals globals locals
expression Python () globals locals globals '__builtins__' expression globals expression
builtinslocals globalseval():>>> x = 1 >>> eval('x+1') 2
(
compile()) mode'exec'eval()None
-
exec(object[, globals[, locals]]) Python object Python () [1] ( "file-input" )
returnyieldexec()Noneglobals globals locals locals exec globals locals
-
filter(function, iterable) iterable function iterable function
Noneiterablefilter(function, iterable)None(item for item in iterable if function(item))None(item for item in iterable if item)function iterable
itertools.filterfalse()
-
class
float([x]) x
10
'+''-''+'NaN (not-a-number) :sign ::= "+" | "-" infinity ::= "Infinity" | "inf" nan ::= "nan" numeric_value ::=
floatnumber|infinity|nannumeric_string ::= [sign]numeric_valuefloatnumberPython "inf" "Inf" "INFINITY" "iNfINity"(Python ) Python
OverflowErrorPython
xfloat(x)x.__float__()0.0:
>>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
3.6 :
-
format(value[, format_spec]) value format_spec "" format_spec value :
format_spec
str(value)format(value, format_spec)type(value).__format__(value, format_spec)value__format__()objectformat_spec format_specTypeError3.4 : format_spec
object().__format__(format_spec)TypeError
-
class
frozenset([iterable]) frozensetiterablefrozensetfrozensetset set, frozensetset,list,tuple,dictcollections
-
getattr(object, name[, default]) object name
getattr(x, 'foobar')x.foobardefaultAttributeError
-
hasattr(object, name) TrueFalse(getattr(object, name)AttributeError)
-
hex(x) Convert an integer number to a lowercase hexadecimal string prefixed with "0x". If x is not a Python
intobject, it has to define an __index__() method that returns an integer. Some examples:>>> hex(255) '0xff' >>> hex(-42) '-0x2a'
16 16 "0x" "0x" :
>>> '%#x' % 255, '%x' % 255, '%X' % 255 ('0xff', 'ff', 'FF') >>> format(255, '#x'), format(255, 'x'), format(255, 'X') ('0xff', 'ff', 'FF') >>> f'{255:#x}', f'{255:x}', f'{255:X}' ('0xff', 'ff', 'FF')
1616
int()16
float.hex()
-
id(object) "" 2
id()CPython : This is the address of the object in memory.
-
input([prompt]) prompt 1 () EOF
EOFError:>>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
-
class
int(x=0) -
class
int(x, base=10) Return an integer object constructed from a number or string x, or return
0if no arguments are given. If x is a number, returnx.__int__(). If x definesx.__trunc__()but notx.__int__(), then return ifx.__trunc__(). For floating point numbers, this truncates towards zero.x base x
bytesbytearraybase+-() n 0 n-1 10-35az(AZ) base 10 0 236 2, 8, 160b/0B,0o/0O,0x/0X0 2, 8, 10, 16int('010', 0)int('010')int('010', 8)3.4 : base
intbasebase.__index__base.__index__base.__int__3.6 :
-
isinstance(object, classinfo) object classinfo ( ) object classinfo () object classinfo
TypeError
-
iter(object[, sentinel]) (iterator) object (
__iter__()) (0__getitem__())TypeErrorsentinel object__next__()object sentinelStopIterationiter()2readline():with open('mydata.txt') as fp: for line in iter(fp.readline, ''): process_line(line)
-
class
list([iterable])
-
map(function, iterable, ...) function iterable iterable function
itertools.starmap()
-
max(iterable, *[, key, default]) -
max(arg1, arg2, *args[, key]) iterable 2
1 iterable iterable 2
2 key 1 (
list.sort()) default defaultValueErrorsorted(iterable, key=keyfunc, reverse=True)[0]heapq.nlargest(1, iterable, key=keyfunc)3.4 : default
-
min(iterable, *[, key, default]) -
min(arg1, arg2, *args[, key]) iterable 2
1 iterable iterable 2
2 key 1 (
list.sort()) default defaultValueErrorsorted(iterable, key=keyfunc)[0]heapq.nsmallest(1, iterable, key=keyfunc)3.4 : default
-
next(iterator[, default]) iterator
__next__()defaultStopIteration
-
class
object objectPython
-
oct(x) Convert an integer number to an octal string prefixed with "0o". The result is a valid Python expression. If x is not a Python
intobject, it has to define an__index__()method that returns an integer. For example:>>> oct(8) '0o10' >>> oct(-56) '-0o70'
If you want to convert an integer number to octal string either with prefix "0o" or not, you can use either of the following ways.
>>> '%#o' % 10, '%o' % 10 ('0o12', '12') >>> format(10, '#o'), format(10, 'o') ('0o12', '12') >>> f'{10:#o}', f'{10:o}' ('0o12', '12')
-
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) file
OSErrorfile :term:path-like object () ( closefd
FalseI/O )mode
'r'()'w''x''a'( Unix )encoding :locale.getpreferredencoding(False)(rawencoding )'r'() 'w''x''a''b''t'() '+'() 'U'() 'r'('rt')'w+b'0'r+b'Python I/O (mode
'b')bytes( mode't')strencodingPython ; Python
buffering () 0 () 1 1 buffering :
-
io.DEFAULT_BUFFER_SIZE4096 8192 - (
isatty()True)
encoding text encoding (
locale.getpreferredencoding()) Pythoncodecserrors ( )
codecs.register_error():'strict'ValueErrorNone'ignore''replace'('?')'surrogateescape'Unicode Private Use Area () U+DC80 U+DCFFsurrogateescape'xmlcharrefreplace'&#nnn;XML'backslashreplace'Python'namereplace'()\N{...}
newline universal newlines ()
None,'','\n','\r','\r\n':- newline
None'\n','\r','\r\n''\n''' - newline
None'\n'os.linesepnewline'''\n'newline'\n'
closefd
FalseclosefdTrue()opener opener (file, flags) opener (
os.openopenerNone)>>> import os >>> dir_fd = os.open('somedir', os.O_RDONLY) >>> def opener(path, flags): ... return os.open(path, flags, dir_fd=dir_fd) ... >>> with open('spamspam.txt', 'w', opener=opener) as f: ... print('This will be written to somedir/spamspam.txt', file=f) ... >>> os.close(dir_fd) # don't leak a file descriptor
open()file objectopen()('w','r','wt','rt', )io.TextIOBase(io.TextIOWrapper)io.BufferedIOBaseio.BufferedReaderio.BufferedWriterio.BufferedRandomrawio.RawIOBaseio.FileIOfileinput(open())ioosos.pathtempfileshutil3.3 :- opener
'x'-
IOErrorOSError - (
'x')FileExistsError
3.4 :3.4 4.0 :
'U'3.5 :-
InterruptedError( PEP 475 ) 'namereplace'
3.6 :os.PathLike- Windows
io.FileIO`:class:`io.RawIOBase
-
-
ord(c) 1 Unicode Unicode
ord('a')97ord('')()8364chr()
-
pow(x, y[, z]) x y ; z x y z (
pow(x, y) % z)pow(x, y)x**yint() ;10**210010**-20.01z x y y
-
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) objects sep file end sep end file flush
str()sep end sep endNoneobjectsprint()endfile
write(string)Nonesys.stdoutprint()file.write(...)file flush
3.3 : flush
-
class
property(fget=None, fset=None, fdel=None, doc=None) property
fget fset fdel doc docstring
x:class C: def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.")
c C
c.xgetterc.x = valuesetterdel c.xdeleterdoc property property fget ()
property()(decorator) property :class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
@propertyvoltage()"getter" voltage "Get the current voltage."property
getter,setter,deleterproperty :class C: def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x
property (
x)property
fget,fset,fdel3.5 :
-
range(stop) -
range(start, stop[, step])
-
repr(object) eval()()__repr__()
-
reversed(seq) (reverse iterator) seq
__reversed__()(__len__()0__getitem__())
-
round(number[, ndigits]) number ndigists ndigits
NoneFor the built-in types supporting
round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, bothround(0.5)andround(-0.5)are0, andround(1.5)is2). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if called with one argument, otherwise of the same type as number.For a general Python object
number,round(number, ndigits)delegates tonumber.__round__(ndigits).round():round(2.675, 2)2.682.67:
-
class
set([iterable]) iterable
setsetsetset set, frozenset
-
setattr(object, name, value) getattr()setattr(x, 'foobar', 123)x.foobar = 123
-
class
slice(stop) -
class
slice(start, stop[, step]) range(start, stop, step)(slice) start stepNonestartstopstep() Numerical Pythona[start:stop:step]a[start:stop, i]itertools.islice()
-
sorted(iterable, *, key=None, reverse=False) iterable
2
key 1 :
key=str.lowerNone()reverse
Truecmp key
functools.cmp_to_key()sort()
-
@staticmethod -
:
class C: @staticmethod def f(arg1, arg2, ...): ...
@staticmethod(decorator)(
C.f()) (C().f())Python Java C++
classmethod()Like all decorators, it is also possible to call
staticmethodas a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:class C: builtin_open = staticmethod(open)
-
class
str(object='') -
class
str(object=b'', encoding='utf-8', errors='strict') -
strstr
-
sum(iterable[, start]) start iterable start
0iterable startsum()''.join(sequence)math.fsum()itertools.chain()
-
super([type[, object-or-type]]) type type
getattr()type
__mro__getattr()super()2 2
isinstance(obj, type)2issubclass(type2, type)()super 2 super super
2 Python "diamond diagram" ()
:
class C(B): def method(self, arg): super().method(arg) # This does the same thing as: # super(C, self).method(arg)
super()super().__getitem__(name)__getattribute__()super()super()[name]super()2
-
tuple([iterable])
-
class
type(object) -
class
type(name, bases, dict) 1object
object.__class__3
classname__name__bases__bases__dict__dict__type:>>> class X: ... a = 1 ... >>> X = type('X', (object,), dict(a=1))
3.6 :
type.__new__:class:type
-
vars([object])
-
zip(*iterables) -
i i 1 :
def zip(*iterables): # zip('ABCD', 'xy') --> Ax By sentinel = object() iterators = [iter(it) for it in iterables] while iterators: result = [] for it in iterators: elem = next(it, sentinel) if elem is sentinel: return result.append(elem) yield tuple(result)
zip(*[iter(s)]*n)nnnnzip()*zip :>>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> list(zipped) [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zip(x, y)) >>> x == list(x2) and y == list(y2) True
-
__import__(name, globals=None, locals=None, fromlist=(), level=0) importlib.import_module()Pythonimport(builtinsbuiltins.__import__)import(PEP 302 )__import__()importlib.import_module()name globals locals fromlist name locals globals
importlevel
0() level__import__()( PEP 328 )name
package.modulename () fromlist nameimport spam:spam = __import__('spam', globals(), locals(), [], 0)
import spam.ham:spam = __import__('spam.ham', globals(), locals(), [], 0)
from spam.ham import eggs, sausage as saus_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage
__import__()spam.ham3.3 : level ( 0 )
| [1] | Unix Windows Mac |