Inbyggda funktioner¶
Python-tolken har ett antal inbyggda funktioner och typer som alltid är tillgängliga. De listas här i alfabetisk ordning.
Inbyggda funktioner |
|||
|---|---|---|---|
E
uppräkna()F
flöde()G
globaler()H
harattr()I
inmatning() |
|||
- abs(number, /)¶
Returnerar det absoluta värdet av ett tal. Argumentet kan vara ett heltal, ett flyttal eller ett objekt som implementerar
__abs__(). Om argumentet är ett komplext tal returneras dess magnitud.
- aiter(async_iterable, /)¶
Returnerar en asynkron iterator för en asynkron iterabel. Motsvarar anrop av
x.__aiter__().Notera: Till skillnad från
iter()haraiter()ingen variant med 2 argument.Added in version 3.10.
- all(iterable, /)¶
Returnerar
Trueom alla element i iterabeln är sanna (eller om iterabeln är tom). Likvärdig med:def all(iterabel): för element i iterabel: if inte element: returnera False returnera sant
- awaitable anext(async_iterator, /)¶
- awaitable anext(async_iterator, default, /)
När den är väntad returneras nästa objekt från den angivna asynchronous iterator, eller standard om den är angiven och iteratorn är uttömd.
Detta är den asynkrona varianten av
next()-byggstenen och fungerar på samma sätt.Detta anropar
__anext__()-metoden för async_iterator och returnerar en awaitable. Awaiting detta returnerar nästa värde i iteratorn. Om default anges returneras det om iteratorn är uttömd, annars uppstårStopAsyncIteration.Added in version 3.10.
- any(iterable, /)¶
Returnerar
Trueom något element i iterabeln är sant. Om iterabeln är tom returnerasFalse. Likvärdig med:def any(iterable): för element i iterabel: if element: returnera True returnera Falskt
- ascii(object, /)¶
Som
repr(), returnera en sträng som innehåller en utskrivbar representation av ett objekt, men escape icke-ASCII-tecken i strängen som returneras avrepr()med hjälp av\x,\uellerU\escapes. Detta genererar en sträng som liknar den som returneras avrepr()i Python 2.
- bin(integer, /)¶
Konvertera ett heltal till en binär sträng med prefixet ”0b”. Resultatet är ett giltigt Python-uttryck. Om integer inte är ett Python
int-objekt måste det definiera en__index__()-metod som returnerar ett heltal. Några exempel:>>> bin(3) '0b11' >>> bin(-10) '-0b1010'
Om prefixet ”0b” önskas eller inte, kan du använda något av följande sätt.
>>> format(14, '#b'), format(14, 'b') ('0b1110', '1110') >>> f'{14:#b}', f'{14:b}' ('0b1110', '1110')
See also
enum.bin()to represent negative values as twos-complement.Se även
format()för mer information.
- class bool(object=False, /)¶
Returnerar ett booleskt värde, dvs. antingen
TrueellerFalse. Argumentet konverteras med hjälp av standardproceduren sanningsprövning. Om argumentet är falskt eller utelämnat returnerasFalse, annars returnerasTrue. Klassenboolär en underklass tillint(se Numeriska typer — int, float, complex). Den kan inte delas upp i ytterligare underklasser. Dess enda instanser ärFalseochTrue(se Booleansk typ - bool).Förändrat i version 3.7: Parametern är nu endast positionsbestämd.
- breakpoint(*args, **kws)¶
Den här funktionen släpper in dig i felsökaren på anropsplatsen. Specifikt anropar den
sys.breakpointhook()och skickarargsochkwsrakt igenom. Som standard anroparsys.breakpointhook()pdb.set_trace()och förväntar sig inga argument. I det här fallet är det en ren bekvämlighetsfunktion så att du inte uttryckligen behöver importerapdbeller skriva så mycket kod för att komma in i felsökaren. Mensys.breakpointhook()kan sättas till någon annan funktion ochbreakpoint()kommer automatiskt att anropa den, så att du kan hoppa in i den debugger du väljer. Omsys.breakpointhook()inte är tillgänglig kommer denna funktion att ge upphov tillRuntimeError.Som standard kan beteendet hos
breakpoint()ändras med miljövariabelnPYTHONBREAKPOINT. Sesys.breakpointhook()för användningsdetaljer.Observera att detta inte är garanterat om
sys.breakpointhook()har ersatts.Utlöser en auditing event
builtins.breakpointmed argumentetbreakpointhook.Added in version 3.7.
- class bytearray(source=b'')
- class bytearray(source, encoding, errors='strict')
Returnerar en ny array av bytes. Klassen
bytearrayär en föränderlig sekvens av heltal i intervallet 0 <= x < 256. Den har de flesta av de vanliga metoderna för muterbara sekvenser, beskrivna i Mutabla sekvenstyper, samt de flesta metoder som typenbyteshar, se Bytes and Bytearray Operations.Den valfria parametern source kan användas för att initiera matrisen på några olika sätt:
Om det är en sträng måste du också ange parametrarna encoding (och eventuellt errors);
bytearray()konverterar sedan strängen till bytes medstr.encode().Om det är ett integer kommer arrayen att ha den storleken och initialiseras med null-bytes.
Om det är ett objekt som överensstämmer med buffer interface, kommer en skrivskyddad buffert av objektet att användas för att initiera bytesmatrisen.
Om det är en iterabel måste det vara en iterabel av heltal i intervallet
0 <= x < 256, som används som det ursprungliga innehållet i matrisen.
Utan argument skapas en array av storleken 0.
Se även Binary Sequence Types — bytes, bytearray, memoryview och Bytearray Objects.
- class bytes(source=b'')
- class bytes(source, encoding, errors='strict')
Returnerar ett nytt ”bytes”-objekt som är en oföränderlig sekvens av heltal i intervallet
0 <= x < 256.bytesär en oföränderlig version avbytearray– den har samma icke-muterande metoder och samma indexerings- och skivningsbeteende.Följaktligen tolkas konstruktörsargument som för
bytearray().Bytesobjekt kan också skapas med literaler, se String and Bytes literals.
Se även Binary Sequence Types — bytes, bytearray, memoryview, Bytes Objects och Bytes and Bytearray Operations.
- callable(object, /)¶
Returnerar
Trueom argumentet object verkar anropbart,Falseom inte. Om detta returnerarTrueär det fortfarande möjligt att ett anrop misslyckas, men om det ärFalsekommer anropet av object aldrig att lyckas. Observera att klasser är anropsbara (anrop av en klass returnerar en ny instans); instanser är anropsbara om deras klass har en__call__()-metod.Added in version 3.2: Denna funktion togs först bort i Python 3.0 och återinfördes sedan i Python 3.2.
- chr(codepoint, /)¶
Returnerar strängen som representerar ett tecken med den angivna Unicode-kodpunkten. Till exempel, vid
chr(97), returneras strängen'a', medan vidchr(8364)returneras strängen'€'. Detta är motsatsen tillord().Det giltiga intervallet för argumentet är från 0 till 1 114 111 (0x10FFFF i bas 16).
ValueErrorkommer att genereras om det ligger utanför detta intervall.
- @classmethod¶
Omvandla en metod till en klassmetod.
En klassmetod tar emot klassen som ett implicit första argument, precis som en instansmetod tar emot instansen. För att deklarera en klassmetod använder du detta idiom:
klass C: @klassmetod def f(cls, arg1, arg2): ...
Formuläret
@classmethodär en funktion decorator – se Function definitions för detaljer.En klassmetod kan anropas antingen på klassen (t.ex.
C.f()) eller på en instans (t.ex.C().f()). Instansen ignoreras med undantag för dess klass. Om en klassmetod anropas för en härledd klass, skickas det härledda klassobjektet som det underförstådda första argumentet.Klassmetoder är annorlunda än statiska metoder i C++ eller Java. Om du vill ha sådana, se
staticmethod()i detta avsnitt. För mer information om klassmetoder, se The standard type hierarchy.Förändrat i version 3.9: Klassmetoder kan nu omsluta andra deskriptorer såsom
property().Förändrat i version 3.10: Klassmetoder ärver nu metodattributen (
__module__,__name__,__qualname__,__doc__och__annotations__) och har ett nytt attribut__wrapped__.Deprecated since version 3.11, removed in version 3.13: Klassmetoder kan inte längre omsluta andra deskriptorer såsom
property().
- compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)¶
Kompilera källan till ett kod- eller AST-objekt. Kodobjekt kan exekveras med
exec()ellereval(). source kan antingen vara en normal sträng, en byte-sträng eller ett AST-objekt. Se dokumentationen för modulenastför information om hur du arbetar med AST-objekt.Argumentet filnamn ska ange den fil som koden lästes från; skicka något igenkännbart värde om den inte lästes från en fil (
'<string>'används ofta).Argumentet mode anger vilken typ av kod som ska kompileras; det kan vara
'exec'om källan består av en sekvens av satser,'eval'om den består av ett enda uttryck, eller'single'om den består av en enda interaktiv sats (i det senare fallet skrivs satser som utvärderas till något annat änNoneut).De valfria argumenten flags och dont_inherit styr vilka compiler options som ska aktiveras och vilka future features som ska tillåtas. Om ingen av dessa är närvarande (eller om båda är noll) kompileras koden med samma flaggor som påverkar koden som anropar
compile(). Om argumentet flags anges och dont_inherit inte anges (eller är noll) används de kompilatoralternativ och framtida uttalanden som anges i argumentet flags utöver de som ändå skulle ha använts. Om dont_inherit är ett heltal som inte är noll så är flags-argumentet det - flaggorna (framtida funktioner och kompilatoralternativ) i den omgivande koden ignoreras.Kompilatoralternativ och framtidssatser specificeras av bitar som kan kombineras bitvis för att specificera flera alternativ. Bitfältet som krävs för att specificera en given framtida funktion kan hittas som attributet
compiler_flagpå_Featureinstansen i__future__modulen. Compiler flags kan hittas iastmodulen, medPyCF_prefix.Argumentet optimize anger kompilatorns optimeringsnivå; standardvärdet
\-1väljer tolkens optimeringsnivå som anges i-O-alternativen. Explicita nivåer är0(ingen optimering;__debug__är sant),1(asserts tas bort,__debug__är falskt) eller2(docstrings tas också bort).This function raises
SyntaxErrororValueErrorif the compiled source is invalid.Om du vill analysera Python-kod till dess AST-representation, se
ast.parse().Utlöser en auditing-händelse
compilemed argumentensourceochfilename. Denna händelse kan också utlösas av implicit kompilering.Observera
När en sträng med flerradig kod kompileras i läget
'single'eller'eval'måste inmatningen avslutas med minst ett tecken för ny rad. Detta för att underlätta upptäckten av ofullständiga och fullständiga satser i modulencode.Varning
Det är möjligt att krascha Python-tolken med en tillräckligt stor/komplex sträng när den kompileras till ett AST-objekt på grund av begränsningar i stackdjupet i Pythons AST-kompilator.
Förändrat i version 3.2: Tillåtet att använda Windows och Mac newlines. Dessutom behöver inmatning i
'exec'-läge inte längre avslutas med en ny rad. Parametern optimize har lagts till.Förändrat i version 3.5: Tidigare skapades
TypeErrornär null bytes påträffades i source.Added in version 3.8:
ast.PyCF_ALLOW_TOP_LEVEL_AWAITcan now be passed in flags to enable support for top-levelawait,async for, andasync with.
- class complex(number=0, /)¶
- class complex(string, /)
- class complex(real=0, imag=0)
Convert a single string or number to a complex number, or create a complex number from real and imaginary parts.
Examples:
>>> complex('+1.23') (1.23+0j) >>> complex('-4.5j') -4.5j >>> complex('-1.23+4.5j') (-1.23+4.5j) >>> complex('\t( -1.23+4.5J )\n') (-1.23+4.5j) >>> complex('-Infinity+NaNj') (-inf+nanj) >>> complex(1.23) (1.23+0j) >>> complex(imag=-4.5) -4.5j >>> complex(-1.23, 4.5) (-1.23+4.5j)
If the argument is a string, it must contain either a real part (in the same format as for
float()) or an imaginary part (in the same format but with a'j'or'J'suffix), or both real and imaginary parts (the sign of the imaginary part is mandatory in this case). The string can optionally be surrounded by whitespaces and the round parentheses'('and')', which are ignored. The string must not contain whitespace between'+','-', the'j'or'J'suffix, and the decimal number. For example,complex('1+2j')is fine, butcomplex('1 + 2j')raisesValueError. More precisely, the input must conform to thecomplexvalueproduction rule in the following grammar, after parentheses and leading and trailing whitespace characters are removed:complexvalue:
floatvalue|floatvalue("j" | "J") |floatvaluesignabsfloatvalue("j" | "J")If the argument is a number, the constructor serves as a numeric conversion like
intandfloat. For a general Python objectx,complex(x)delegates tox.__complex__(). If__complex__()is not defined then it falls back to__float__(). If__float__()is not defined then it falls back to__index__().If two arguments are provided or keyword arguments are used, each argument may be any numeric type (including complex). If both arguments are real numbers, return a complex number with the real component real and the imaginary component imag. If both arguments are complex numbers, return a complex number with the real component
real.real-imag.imagand the imaginary componentreal.imag+imag.real. If one of arguments is a real number, only its real component is used in the above expressions.See also
complex.from_number()which only accepts a single numeric argument.If all arguments are omitted, returns
0j.The complex type is described in Numeriska typer — int, float, complex.
Förändrat i version 3.6: Grouping digits with underscores as in code literals is allowed.
Förändrat i version 3.8: Falls back to
__index__()if__complex__()and__float__()are not defined.Ersatt sedan version 3.14: Passing a complex number as the real or imag argument is now deprecated; it should only be passed as a single positional argument.
- delattr(object, name, /)¶
This is a relative of
setattr(). The arguments are an object and a string. The string must be the name of one of the object’s attributes. The function deletes the named attribute, provided the object allows it. For example,delattr(x, 'foobar')is equivalent todel x.foobar. name need not be a Python identifier (seesetattr()).
- class dict(**kwargs)
- class dict(mapping, /, **kwargs)
- class dict(iterable, /, **kwargs)
Create a new dictionary. The
dictobject is the dictionary class. Seedictand Mapping Types — dict for documentation about this class.For other containers see the built-in
list,set, andtupleclasses, as well as thecollectionsmodule.
- dir()¶
- dir(object, /)
Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.
If the object has a method named
__dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom__getattr__()or__getattribute__()function to customize the waydir()reports their attributes.If the object does not provide
__dir__(), the function tries its best to gather information from the object’s__dict__attribute, if defined, and from its type object. The resulting list is not necessarily complete and may be inaccurate when the object has a custom__getattr__().The default
dir()mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:If the object is a module object, the list contains the names of the module’s attributes.
If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.
The resulting list is sorted alphabetically. For example:
>>> 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']
Observera
Because
dir()is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.
- divmod(a, b, /)¶
Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as
(a // b, a % b). For floating-point numbers the result is(q, a % b), where q is usuallymath.floor(a / b)but may be 1 less than that. In any caseq * b + a % bis very close to a, ifa % bis non-zero it has the same sign as b, and0 <= abs(a % b) < abs(b).
- enumerate(iterable, start=0)¶
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The
__next__()method of the iterator returned byenumerate()returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over 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')]
Equivalent to:
def enumerate(iterable, start=0): n = start for elem in iterable: yield n, elem n += 1
- eval(source, /, globals=None, locals=None)¶
- Parametrar:
source (
str| code object) – A Python expression.globals (
dict|None) – The global namespace (default:None).locals (mapping |
None) – The local namespace (default:None).
- Returnerar:
The result of the evaluated expression.
- Raises:
Syntax errors are reported as exceptions.
Varning
This function executes arbitrary code. Calling it with untrusted user-supplied input will lead to security vulnerabilities.
The source argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals mappings as global and local namespace. If the globals dictionary is present and does not contain a value for the key
__builtins__, a reference to the dictionary of the built-in modulebuiltinsis inserted under that key before source is parsed. Overriding__builtins__can be used to restrict or change the available names, but this is not a security mechanism: the executed code can still access all builtins. If the locals mapping is omitted it defaults to the globals dictionary. If both mappings are omitted, the source is executed with the globals and locals in the environment whereeval()is called. Note, eval() will only have access to the nested scopes (non-locals) in the enclosing environment if they are already referenced in the scope that is callingeval()(e.g. via anonlocalstatement).Example:
>>> x = 1 >>> eval('x+1') 2
This function can also be used to execute arbitrary code objects (such as those created by
compile()). In this case, pass a code object instead of a string. If the code object has been compiled with'exec'as the mode argument,eval()'s return value will beNone.Hints: dynamic execution of statements is supported by the
exec()function. Theglobals()andlocals()functions return the current global and local dictionary, respectively, which may be useful to pass around for use byeval()orexec().If the given source is a string, then leading and trailing spaces and tabs are stripped.
See
ast.literal_eval()for a function that can safely evaluate strings with expressions containing only literals.Raises an auditing event
execwith the code object as the argument. Code compilation events may also be raised.Förändrat i version 3.13: The globals and locals arguments can now be passed as keywords.
Förändrat i version 3.13: The semantics of the default locals namespace have been adjusted as described for the
locals()builtin.
- exec(source, /, globals=None, locals=None, *, closure=None)¶
Varning
This function executes arbitrary code. Calling it with untrusted user-supplied input will lead to security vulnerabilities.
This function supports dynamic execution of Python code. source must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1] If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section File input in the Reference Manual). Be aware that the
nonlocal,yield, andreturnstatements may not be used outside of function definitions even within the context of code passed to theexec()function. The return value isNone.In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary (and not a subclass of dictionary), which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at the module level, globals and locals are the same dictionary.
Observera
When
execgets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition. This means functions and classes defined in the executed code will not be able to access variables assigned at the top level (as the ”top level” variables are treated as class variables in a class definition).If the globals dictionary does not contain a value for the key
__builtins__, a reference to the dictionary of the built-in modulebuiltinsis inserted under that key. Overriding__builtins__can be used to restrict or change the available names, but this is not a security mechanism: the executed code can still access all builtins.The closure argument specifies a closure–a tuple of cellvars. It’s only valid when the object is a code object containing free (closure) variables. The length of the tuple must exactly match the length of the code object’s
co_freevarsattribute.Raises an auditing event
execwith the code object as the argument. Code compilation events may also be raised.Observera
The built-in functions
globals()andlocals()return the current global and local namespace, respectively, which may be useful to pass around for use as the second and third argument toexec().Observera
The default locals act as described for function
locals()below. Pass an explicit locals dictionary if you need to see effects of the code on locals after functionexec()returns.Förändrat i version 3.11: Added the closure parameter.
Förändrat i version 3.13: The globals and locals arguments can now be passed as keywords.
Förändrat i version 3.13: The semantics of the default locals namespace have been adjusted as described for the
locals()builtin.
- filter(function, iterable, /)¶
Construct an iterator from those elements of iterable for which function is true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is
None, the identity function is assumed, that is, all elements of iterable that are false are removed.Note that
filter(function, iterable)is equivalent to the generator expression(item for item in iterable if function(item))if function is notNoneand(item for item in iterable if item)if function isNone.See
itertools.filterfalse()for the complementary function that returns elements of iterable for which function is false.
- class float(number=0.0, /)¶
- class float(string, /)
Return a floating-point number constructed from a number or a string.
Examples:
>>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be
'+'or'-'; a'+'sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or positive or negative infinity. More precisely, the input must conform to thefloatvalueproduction rule in the following grammar, after leading and trailing whitespace characters are removed:sign: "+" | "-" infinity: "Infinity" | "inf" nan: "nan" digit: <a Unicode decimal digit, i.e. characters in Unicode general category Nd> digitpart:
digit(["_"]digit)* number: [digitpart] "."digitpart|digitpart["."] exponent: ("e" | "E") [sign]digitpartfloatnumber:number[exponent] absfloatvalue:floatnumber|infinity|nanfloatvalue: [sign]absfloatvalueCase is not significant, so, for example, ”inf”, ”Inf”, ”INFINITY”, and ”iNfINity” are all acceptable spellings for positive infinity.
Otherwise, if the argument is an integer or a floating-point number, a floating-point number with the same value (within Python’s floating-point precision) is returned. If the argument is outside the range of a Python float, an
OverflowErrorwill be raised.For a general Python object
x,float(x)delegates tox.__float__(). If__float__()is not defined then it falls back to__index__().See also
float.from_number()which only accepts a numeric argument.If no argument is given,
0.0is returned.The float type is described in Numeriska typer — int, float, complex.
Förändrat i version 3.6: Grouping digits with underscores as in code literals is allowed.
Förändrat i version 3.7: Parametern är nu endast positionsbestämd.
Förändrat i version 3.8: Falls back to
__index__()if__float__()is not defined.
- format(value, format_spec='', /)¶
Convert a value to a ”formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument; however, there is a standard formatting syntax that is used by most built-in types: Format specification mini-language.
The default format_spec is an empty string which usually gives the same effect as calling
str(value).A call to
format(value, format_spec)is translated totype(value).__format__(value, format_spec)which bypasses the instance dictionary when searching for the value’s__format__()method. ATypeErrorexception is raised if the method search reachesobjectand the format_spec is non-empty, or if either the format_spec or the return value are not strings.Förändrat i version 3.4:
object().__format__(format_spec)raisesTypeErrorif format_spec is not an empty string.
- class frozenset(iterable=(), /)
Return a new
frozensetobject, optionally with elements taken from iterable.frozensetis a built-in class. Seefrozensetand Set Types — set, frozenset for documentation about this class.For other containers see the built-in
set,list,tuple, anddictclasses, as well as thecollectionsmodule.
- getattr(object, name, /)¶
- getattr(object, name, default, /)
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example,
getattr(x, 'foobar')is equivalent tox.foobar. If the named attribute does not exist, default is returned if provided, otherwiseAttributeErroris raised. name need not be a Python identifier (seesetattr()).Observera
Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with
getattr().
- globals()¶
Return the dictionary implementing the current module namespace. For code within functions, this is set when the function is defined and remains the same regardless of where the function is called.
- hasattr(object, name, /)¶
The arguments are an object and a string. The result is
Trueif the string is the name of one of the object’s attributes,Falseif not. (This is implemented by callinggetattr(object, name)and seeing whether it raises anAttributeErroror not.)
- hash(object, /)¶
Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).
Observera
For objects with custom
__hash__()methods, note thathash()truncates the return value based on the bit width of the host machine.
- help()¶
- help(request)
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking
help(), it means that the parameters prior to the slash are positional-only. For more info, see the FAQ entry on positional-only parameters.This function is added to the built-in namespace by the
sitemodule.
- hex(integer, /)¶
Convert an integer number to a lowercase hexadecimal string prefixed with ”0x”. If integer is not a Python
intobject, it has to define an__index__()method that returns an integer. Some examples:>>> hex(255) '0xff' >>> hex(-42) '-0x2a'
If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:
>>> '%#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')
Se även
format()för mer information.See also
int()for converting a hexadecimal string to an integer using a base of 16.Observera
To obtain a hexadecimal string representation for a float, use the
float.hex()method.
- id(object, /)¶
Return the ”identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same
id()value.Detaljerad implementering av CPython: This is the address of the object in memory.
Raises an auditing event
builtins.idwith argumentid.
- input()¶
- input(prompt, /)
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read,
EOFErroris raised. Example:>>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus"
If the
readlinemodule was loaded, theninput()will use it to provide elaborate line editing and history features.Raises an auditing event
builtins.inputwith argumentpromptbefore reading inputRaises an auditing event
builtins.input/resultwith the result after successfully reading input.
- class int(number=0, /)¶
- class int(string, /, base=10)
Return an integer object constructed from a number or a string, or return
0if no arguments are given.Examples:
>>> int(123.45) 123 >>> int('123') 123 >>> int(' -12_345\n') -12345 >>> int('FACE', 16) 64206 >>> int('0xface', 0) 64206 >>> int('01110011', base=2) 115
If the argument defines
__int__(),int(x)returnsx.__int__(). If the argument defines__index__(), it returnsx.__index__(). For floating-point numbers, this truncates towards zero.If the argument is not a number or if base is given, then it must be a string,
bytes, orbytearrayinstance representing an integer in radix base. Optionally, the string can be preceded by+or-(with no space in between), have leading zeros, be surrounded by whitespace, and have single underscores interspersed between digits.A base-n integer string contains digits, each representing a value from 0 to n-1. The values 0–9 can be represented by any Unicode decimal digit. The values 10–35 can be represented by
atoz(orAtoZ). The default base is 10. The allowed bases are 0 and 2–36. Base-2, -8, and -16 strings can be optionally prefixed with0b/0B,0o/0O, or0x/0X, as with integer literals in code. For base 0, the string is interpreted in a similar way to an integer literal in code, in that the actual base is 2, 8, 10, or 16 as determined by the prefix. Base 0 also disallows leading zeros:int('010', 0)is not legal, whileint('010')andint('010', 8)are.The integer type is described in Numeriska typer — int, float, complex.
Förändrat i version 3.4: If base is not an instance of
intand the base object has abase.__index__method, that method is called to obtain an integer for the base. Previous versions usedbase.__int__instead ofbase.__index__.Förändrat i version 3.6: Grouping digits with underscores as in code literals is allowed.
Förändrat i version 3.7: The first parameter is now positional-only.
Förändrat i version 3.8: Falls back to
__index__()if__int__()is not defined.Förändrat i version 3.11:
intstring inputs and string representations can be limited to help avoid denial of service attacks. AValueErroris raised when the limit is exceeded while converting a string to anintor when converting anintinto a string would exceed the limit. See the integer string conversion length limitation documentation.Förändrat i version 3.14:
int()no longer delegates to the__trunc__()method.
- isinstance(object, classinfo, /)¶
Return
Trueif the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. If object is not an object of the given type, the function always returnsFalse. If classinfo is a tuple of type objects (or recursively, other such tuples) or a Typ av fackförening of multiple types, returnTrueif object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, aTypeErrorexception is raised.TypeErrormay not be raised for an invalid type if an earlier check succeeds.Förändrat i version 3.10: classinfo can be a Typ av fackförening.
- issubclass(class, classinfo, /)¶
Return
Trueif class is a subclass (direct, indirect, or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects (or recursively, other such tuples) or a Typ av fackförening, in which case returnTrueif class is a subclass of any entry in classinfo. In any other case, aTypeErrorexception is raised.Förändrat i version 3.10: classinfo can be a Typ av fackförening.
- iter(iterable, /)¶
- iter(callable, sentinel, /)
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, the single argument must be a collection object which supports the iterable protocol (the
__iter__()method), or it must support the sequence protocol (the__getitem__()method with integer arguments starting at0). If it does not support either of those protocols,TypeErroris raised. If the second argument, sentinel, is given, then the first argument must be a callable object. The iterator created in this case will call callable with no arguments for each call to its__next__()method; if the value returned is equal to sentinel,StopIterationwill be raised, otherwise the value will be returned.See also Iterator-typer.
One useful application of the second form of
iter()is to build a block-reader. For example, reading fixed-width blocks from a binary database file until the end of file is reached:from functools import partial with open('mydata.db', 'rb') as f: for block in iter(partial(f.read, 64), b''): process_block(block)
- len(object, /)¶
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
Detaljerad implementering av CPython:
lenraisesOverflowErroron lengths larger thansys.maxsize, such asrange(2 ** 100).
- class list(iterable=(), /)
Rather than being a function,
listis actually a mutable sequence type, as documented in Listor and Sekvenstyper — list, tuple, range.
- locals()¶
Return a mapping object representing the current local symbol table, with variable names as the keys, and their currently bound references as the values.
At module scope, as well as when using
exec()oreval()with a single namespace, this function returns the same namespace asglobals().At class scope, it returns the namespace that will be passed to the metaclass constructor.
When using
exec()oreval()with separate local and global arguments, it returns the local namespace passed in to the function call.In all of the above cases, each call to
locals()in a given frame of execution will return the same mapping object. Changes made through the mapping object returned fromlocals()will be visible as assigned, reassigned, or deleted local variables, and assigning, reassigning, or deleting local variables will immediately affect the contents of the returned mapping object.In an optimized scope (including functions, generators, and coroutines), each call to
locals()instead returns a fresh dictionary containing the current bindings of the function’s local variables and any nonlocal cell references. In this case, name binding changes made via the returned dict are not written back to the corresponding local variables or nonlocal cell references, and assigning, reassigning, or deleting local variables and nonlocal cell references does not affect the contents of previously returned dictionaries.Calling
locals()as part of a comprehension in a function, generator, or coroutine is equivalent to calling it in the containing scope, except that the comprehension’s initialised iteration variables will be included. In other scopes, it behaves as if the comprehension were running as a nested function.Calling
locals()as part of a generator expression is equivalent to calling it in a nested generator function.Förändrat i version 3.12: The behaviour of
locals()in a comprehension has been updated as described in PEP 709.Förändrat i version 3.13: As part of PEP 667, the semantics of mutating the mapping objects returned from this function are now defined. The behavior in optimized scopes is now as described above. Aside from being defined, the behaviour in other scopes remains unchanged from previous versions.
- map(function, iterable, /, *iterables, strict=False)¶
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterables arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. If strict is
Trueand one of the iterables is exhausted before the others, aValueErroris raised. For cases where the function inputs are already arranged into argument tuples, seeitertools.starmap().Förändrat i version 3.14: Added the strict parameter.
- max(iterable, /, *, key=None)¶
- max(iterable, /, *, default, key=None)
- max(arg1, arg2, /, *args, key=None)
Return the largest item in an iterable or the largest of two or more arguments.
If one positional argument is provided, it should be an iterable. The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.
There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for
list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, aValueErroris raised.If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as
sorted(iterable, key=keyfunc, reverse=True)[0]andheapq.nlargest(1, iterable, key=keyfunc).Förändrat i version 3.4: Added the default keyword-only parameter.
Förändrat i version 3.8: The key can be
None.
- class memoryview(object)
Return a ”memory view” object created from the given argument. See Minnesvy for more information.
- min(iterable, /, *, key=None)¶
- min(iterable, /, *, default, key=None)
- min(arg1, arg2, /, *args, key=None)
Return the smallest item in an iterable or the smallest of two or more arguments.
If one positional argument is provided, it should be an iterable. The smallest item in the iterable is returned. If two or more positional arguments are provided, the smallest of the positional arguments is returned.
There are two optional keyword-only arguments. The key argument specifies a one-argument ordering function like that used for
list.sort(). The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, aValueErroris raised.If multiple items are minimal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as
sorted(iterable, key=keyfunc)[0]andheapq.nsmallest(1, iterable, key=keyfunc).Förändrat i version 3.4: Added the default keyword-only parameter.
Förändrat i version 3.8: The key can be
None.
- next(iterator, /)¶
- next(iterator, default, /)
Retrieve the next item from the iterator by calling its
__next__()method. If default is given, it is returned if the iterator is exhausted, otherwiseStopIterationis raised.
- class object¶
This is the ultimate base class of all other classes. It has methods that are common to all instances of Python classes. When the constructor is called, it returns a new featureless object. The constructor does not accept any arguments.
Observera
objectinstances do not have__dict__attributes, so you can’t assign arbitrary attributes to an instance ofobject.
- oct(integer, /)¶
Convert an integer number to an octal string prefixed with ”0o”. The result is a valid Python expression. If integer 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 an octal string either with the 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')
Se även
format()för mer information.
- open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)¶
Open file and return a corresponding file object. If the file cannot be opened, an
OSErroris raised. See Reading and Writing Files for more examples of how to use this function.file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless closefd is set to
False.)mode is an optional string that specifies the mode in which the file is opened. It defaults to
'r'which means open for reading in text mode. Other common values are'w'for writing (truncating the file if it already exists),'x'for exclusive creation, and'a'for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform-dependent:locale.getencoding()is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:Character
Meaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'öppen för exklusiv skapelse, misslyckas om filen redan finns
'a'öppen för skrivning, läggs till i slutet av filen om den finns
'b'binärt läge
't'textläge (standard)
'+'öppen för uppdatering (läsning och skrivning)
Standardläget är
'r'(öppen för läsning av text, en synonym till'rt'). Lägena'w+'och'w+b'öppnar och trunkerar filen. Lägena'r+'och'r+b'öppnar filen utan trunkering.Som nämndes i Overview skiljer Python mellan binär och text I/O. Filer som öppnas i binärt läge (inklusive
'b'i mode-argumentet) returnerar innehållet sombytes-objekt utan någon avkodning. I textläge (standard, eller när't'ingår i mode-argumentet) returneras filens innehåll somstr, där bytena först har avkodats med en plattformsberoende kodning eller med den angivna kodningen om den anges.Observera
Python är inte beroende av det underliggande operativsystemets uppfattning om textfiler; all bearbetning görs av Python självt och är därför plattformsoberoende.
buffering är ett valfritt heltal som används för att ställa in buffringspolicyn. Ange 0 för att stänga av buffring (endast tillåtet i binärt läge), 1 för att välja linjebuffring (endast användbart när du skriver i textläge) och ett heltal > 1 för att ange storleken i byte på en buffert med fast storlek. Observera att om du anger en buffertstorlek på det här sättet gäller det för binärt buffrad I/O, men
TextIOWrapper(dvs. filer som öppnas medmode='r+') skulle ha en annan buffring. För att inaktivera buffring iTextIOWrapper, överväg att användawrite_throughflaggan förio.TextIOWrapper.reconfigure(). När inget buffering-argument anges fungerar standardpolicyn för buffring på följande sätt:Binära filer buffras i bitar av fast storlek; storleken på bufferten är
max(min(blocksize, 8 MiB), DEFAULT_BUFFER_SIZE)när enhetens blockstorlek är tillgänglig. På de flesta system är bufferten vanligtvis 128 kilobyte lång.”Interaktiva” textfiler (filer för vilka
isatty()returnerarTrue) använder radbuffring. Andra textfiler använder den policy som beskrivs ovan för binära filer.
encoding är namnet på den kodning som används för att avkoda eller koda filen. Detta bör endast användas i textläge. Standardkodningen är plattformsberoende (oavsett vad
locale.getencoding()returnerar), men alla text encoding som stöds av Python kan användas. Se modulencodecsför en lista över kodningar som stöds.errors är en valfri sträng som anger hur kodnings- och avkodningsfel ska hanteras - detta kan inte användas i binärt läge. En mängd olika standardfelhanterare finns tillgängliga (listade under Error Handlers), men alla felhanteringsnamn som har registrerats med
codecs.register_error()är också giltiga. Standardnamnen inkluderar:'strict'för att skapa ettValueErrorundantag om det finns ett kodningsfel. StandardvärdetNonehar samma effekt.'ignore'ignorerar fel. Observera att om du ignorerar kodningsfel kan det leda till dataförlust.'replace'gör att en ersättningsmarkör (t.ex.'?') infogas där det finns felaktiga data.'surrogateescape'kommer att representera alla felaktiga byte som låga surrogatkodsenheter från U+DC80 till U+DCFF. Dessa surrogatkodsenheter kommer sedan att omvandlas tillbaka till samma byte när felhanterarensurrogateescapeanvänds vid skrivning av data. Detta är användbart för att bearbeta filer i en okänd kodning.'xmlcharrefreplace'stöds endast när du skriver till en fil. Tecken som inte stöds av kodningen ersätts med lämplig XML-teckenreferens&#nnn;.'backslashreplace'ersätter missbildade data med Pythons bakåtstreckade escape-sekvenser.'namereplace'(stöds också endast vid skrivning) ersätter tecken som inte stöds medN{...}escape-sekvenser.
newline bestämmer hur man analyserar nya radtecken från flödet. Det kan vara
None,'','\n','\r'och'\r\n'. Det fungerar på följande sätt:Om newline är
Noneaktiveras universal newlines-läget när indata läses från strömmen. Rader i inmatningen kan sluta på'\n','\r'eller'\r\n', och dessa översätts till'\n'innan de returneras till den som anropar. Om det är''aktiveras universal newlines mode, men radavslut returneras till uppringaren oöversatta. Om det har något av de andra lagliga värdena avslutas inmatningsraderna endast med den angivna strängen, och radavslutningen returneras till den som ringer upp oöversatt.Om newline är
Nonenär utdata skrivs till strömmen, översätts alla'\n'-tecken som skrivs till systemets standardradavgränsare,os.linesep. Om newline är''eller'\n'sker ingen översättning. Om newline är något av de andra lagliga värdena översätts alla'\n'-tecken som skrivs till den angivna strängen.
Om closefd är
Falseoch en filbeskrivare istället för ett filnamn har angetts, kommer den underliggande filbeskrivaren att hållas öppen när filen stängs. Om ett filnamn anges måste closefd varaTrue(standard), annars kommer ett fel att uppstå.En anpassad öppnare kan användas genom att skicka en anropsbar som opener. Den underliggande filbeskrivaren för filobjektet erhålls sedan genom att anropa opener med (file, flags). opener måste returnera en öppen filbeskrivare (att skicka
os.opensom opener resulterar i funktionalitet som liknar att skickaNone).Den nyskapade filen är icke-ärftlig.
I följande exempel används parametern dir_fd i funktionen
os.open()för att öppna en fil i förhållande till en viss katalog:>>> 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
Typen av file object som returneras av funktionen
open()beror på läget. Näropen()används för att öppna en fil i textläge ('w','r','wt','rt', etc.) returneras en underklass avio.TextIOBase(specifiktio.TextIOWrapper). När den används för att öppna en fil i binärt läge med buffring är den returnerade klassen en underklass tillio.BufferedIOBase. Den exakta klassen varierar: i binärt läsläge returneras enio.BufferedReader, i binärt skrivläge och binärt append-läge returneras enio.BufferedWriteroch i läs-/skrivläge returneras enio.BufferedRandom. När buffringen är inaktiverad returneras råströmmen, en underklass tillio.RawIOBase,io.FileIO.Se även filhanteringsmodulerna, till exempel
fileinput,io(däropen()deklareras),os,os.path,tempfileochshutil.Skapar en auditing event
openmed argumentenpath,mode,flags.Argumenten
modeochflagskan ha ändrats eller härletts från det ursprungliga anropet.Förändrat i version 3.3:
Parametern opener har lagts till.
Läget
'x'lades till.FileExistsErrorvisas nu om filen som öppnades i exklusivt skapande-läge ('x') redan existerar.
Förändrat i version 3.4:
Filen är nu inte ärftlig.
Förändrat i version 3.5:
Om systemanropet avbryts och signalhanteraren inte ger upphov till ett undantag, försöker funktionen nu göra om systemanropet istället för att ge upphov till ett
InterruptedError-undantag (se PEP 475 för förklaringen).Felhanteraren
'namereplace'har lagts till.
Förändrat i version 3.6:
Stöd har lagts till för att acceptera objekt som implementerar
os.PathLike.I Windows kan öppnandet av en konsolbuffert returnera en annan underklass av
io.RawIOBaseänio.FileIO.
Förändrat i version 3.11: Läget
'Uhar tagits bort.
- ord(character, /)¶
Return the ordinal value of a character.
If the argument is a one-character string, return the Unicode code point of that character. For example,
ord('a')returns the integer97andord('€')(Euro sign) returns8364. This is the inverse ofchr().If the argument is a
bytesorbytearrayobject of length 1, return its single byte value. For example,ord(b'a')returns the integer97.
- pow(base, exp, mod=None)¶
Returnerar bas till potensen exp; om mod finns, returneras bas till potensen exp, modulo mod (beräknas effektivare än
pow(bas, exp) % mod). Formenpow(base, exp)med två argument är likvärdig med att använda potensoperatorn:base**exp.When arguments are builtin numeric types with mixed operand types, the coercion rules for binary arithmetic operators apply. For
intoperands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example,pow(10, 2)returns100, butpow(10, -2)returns0.01. For a negative base of typeintorfloatand a non-integral exponent, a complex result is delivered. For example,pow(-9, 0.5)returns a value close to3j. Whereas, for a negative base of typeintorfloatwith an integral exponent, a float result is delivered. For example,pow(-9, 2.0)returns81.0.För
int-operanderna base och exp gäller att om mod förekommer måste mod också vara av heltalstyp och mod måste vara icke-noll. Om mod finns och exp är negativ, måste base vara relativt primtal till mod. I så fall returneraspow(inv_base, -exp, mod), där inv_base är en invers till base modulo mod.Här är ett exempel på att beräkna en invers för
38modulo97:>>> pow(38, -1, mod=97) 23 >>> 23 * 38 % 97 == 1 True
Förändrat i version 3.8: För
int-operander tillåter nu treargumentformen avpowatt det andra argumentet är negativt, vilket möjliggör beräkning av modulära inverser.Förändrat i version 3.8: Tillåt nyckelordsargument. Tidigare stöddes endast positionella argument.
- print(*objects, sep=' ', end='\n', file=None, flush=False)¶
Skriver ut objekt till textflödet file, separerade med sep och följda av end. sep, end, file och flush, om de finns, måste anges som nyckelordsargument.
Alla argument som inte är nyckelord konverteras till strängar som
str()gör och skrivs till strömmen, separerade med sep och följda av end. Både sep och end måste vara strängar; de kan också varaNone, vilket innebär att standardvärdena används. Om inga objekt anges kommerprint()bara att skriva end.Argumentet file måste vara ett objekt med en
write(string)-metod; om det inte finns eller om det ärNone, kommersys.stdoutatt användas. Eftersom utskrivna argument konverteras till textsträngar kanprint()inte användas med filobjekt i binärt läge. För dessa används iställetfile.write(...).Buffring av utdata bestäms vanligtvis av file. Men om flush är true, spolas strömmen med våld.
Förändrat i version 3.3: Lagt till nyckelordsargumentet flush.
- class property(fget=None, fset=None, fdel=None, doc=None)¶
Returnerar ett egenskapsattribut.
fget är en funktion för att hämta ett attributvärde. fset är en funktion för att ställa in ett attributvärde. fdel är en funktion för att ta bort ett attributvärde. Och doc skapar en docstring för attributet.
En typisk användning är att definiera ett hanterat attribut
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.")
Om c är en instans av C, kommer
c.xatt anropa getter,c.x = valuekommer att anropa setter ochdel c.xdeleter.Om den anges kommer doc att vara docstring för egenskapens attribut. Annars kommer egenskapen att kopiera fgets docstring (om den finns). Detta gör det möjligt att skapa skrivskyddade egenskaper enkelt genom att använda
property()som en decorator:class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage
Dekoratorn
@propertyförvandlar metodenvoltage()till en ”getter” för ett skrivskyddat attribut med samma namn och sätter docstring för voltage till ”Get the current voltage”- @getter¶
- @setter¶
- @deleter¶
Ett egenskapsobjekt har metoderna
getter,etterochdeletersom kan användas som dekoratorer som skapar en kopia av egenskapen med motsvarande accessorfunktion inställd på den dekorerade funktionen. Detta förklaras bäst med ett exempel: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
Denna kod är exakt likvärdig med det första exemplet. Var noga med att ge de ytterligare funktionerna samma namn som den ursprungliga egenskapen (
xi det här fallet.)Det returnerade egenskapsobjektet har också attributen
fget,fsetochfdelsom motsvarar konstruktörens argument.
Förändrat i version 3.5: Dokumentationen av property-objekt är nu skrivbar.
- __name__¶
Attribut som innehåller namnet på egenskapen. Namnet på egenskapen kan ändras vid körning.
Added in version 3.13.
- class range(stop, /)
- class range(start, stop, step=1, /)
I stället för att vara en funktion är
rangefaktiskt en oföränderlig sekvenstyp, vilket dokumenteras i Ranges och Sekvenstyper — list, tuple, range.
- repr(object, /)¶
Returnerar en sträng som innehåller en utskriftsvänlig representation av ett objekt. För många typer försöker denna funktion returnera en sträng som skulle ge ett objekt med samma värde när den skickas till
eval(); annars är representationen en sträng inom hakparenteser som innehåller namnet på objektets typ tillsammans med ytterligare information, ofta inklusive objektets namn och adress. En klass kan styra vad denna funktion returnerar för sina instanser genom att definiera en__repr__()-metod. Omsys.displayhook()inte är tillgänglig kommer denna funktion att ge upphov tillRuntimeError.Denna klass har en anpassad representation som kan utvärderas:
class Person: def __init__(self, name, age): self.name = name self.age = age def __repr__(self): return f"Person('{self.name}', {self.age})"
- reversed(object, /)¶
Returnera en omvänd iterator. Argumentet måste vara ett objekt som har en
__reversed__()-metod eller stöder sekvensprotokollet (metoden__len__()och metoden__getitem__()med heltal som argument som börjar på0).
- round(number, ndigits=None)¶
Returnerar tal avrundat till siffrors precision efter decimaltecknet. Om ndigits utelämnas eller är
None, returneras det närmaste heltalet till indata.För de inbyggda typer som stöder
round()avrundas värden till närmaste multipel av 10 i potens minus ndigits; om två multiplar är lika nära avrundas till det jämna valet (så till exempel är båderound(0.5)ochround(-0.5)0, ochround(1.5)är2). Alla heltalsvärden är giltiga för siffror (positiva, noll eller negativa). Returvärdet är ett heltal om ndigits utelämnas ellerNone. I annat fall har returvärdet samma typ som number.För ett allmänt Python-objekt
numberdelegerarroundtillnumber.__round__.Observera
Beteendet hos
round()för flyttal kan vara överraskande: till exempel gerround(2,675, 2)2,67istället för det förväntade2,68. Detta är inte en bugg: det är ett resultat av det faktum att de flesta decimalfraktioner inte kan representeras exakt som ett flyttal. Se Floating-Point Arithmetic: Issues and Limitations för mer information.
- class set(iterable=(), /)
Returnerar ett nytt
set-objekt, eventuellt med element hämtade från iterable.setär en inbyggd klass. Sesetoch Set Types — set, frozenset för dokumentation om denna klass.För andra behållare se de inbyggda klasserna
frozenset,list,tupleochdict, samt modulencollections.
- setattr(object, name, value, /)¶
Detta är motsvarigheten till
getattr(). Argumenten är ett objekt, en sträng och ett godtyckligt värde. Strängen kan namnge ett befintligt attribut eller ett nytt attribut. Funktionen tilldelar värdet till attributet, förutsatt att objektet tillåter det. Exempelvis ärsetattr(x, 'foobar', 123)likvärdigt medx.foobar = 123.name behöver inte vara en Python-identifierare enligt definitionen i Names (identifiers and keywords) om inte objektet väljer att tillämpa detta, t.ex. i en anpassad
__getattribute__()eller via__slots__. Ett attribut vars namn inte är en identifierare kommer inte att vara tillgängligt med hjälp av punktnotationen, men är tillgängligt viagetattr()etc.Observera
Eftersom private name mangling sker vid kompilering måste man manuellt mangla ett privat attributs (attribut med två inledande understreck) namn för att kunna ställa in det med
setattr().
- class slice(stop, /)¶
- class slice(start, stop, step=None, /)
Returnerar ett slice-objekt som representerar den uppsättning index som anges av
range(start, stop, step). Argumenten start och step är som standardNone.Slice objects are also generated when slicing syntax is used. For example:
a[start:stop:step]ora[start:stop, i].See
itertools.islice()for an alternate version that returns an iterator.
- sorted(iterable, /, *, key=None, reverse=False)¶
Returnerar en ny sorterad lista från objekten i iterable.
Har två valfria argument som måste anges som nyckelordsargument.
key anger en funktion med ett argument som används för att extrahera en jämförelsenyckel från varje element i iterable (t.ex.
key=str.lower). Standardvärdet ärNone(jämför elementen direkt).reverse är ett booleanskt värde. Om värdet är satt till
Truesorteras listelementen som om varje jämförelse vore omvänd.Använd
functools.cmp_to_key()för att konvertera en gammaldags cmp-funktion till en key-funktion.Den inbyggda funktionen
sorted()är garanterat stabil. En sortering är stabil om den garanterar att den inte ändrar den relativa ordningen för element som jämförs lika — detta är användbart för sortering i flera omgångar (t.ex. sortera efter avdelning, sedan efter lönegrad).The sort algorithm uses only
<comparisons between items. While defining an__lt__()method will suffice for sorting, PEP 8 recommends that all six rich comparisons be implemented. This will help avoid bugs when using the same data with other ordering tools such asmax()that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call the reflected__gt__()method.För sorteringsexempel och en kort sorteringshandledning, se Sorting Techniques.
- @staticmethod¶
Omvandla en metod till en statisk metod.
En statisk metod får inte något implicit första argument. För att deklarera en statisk metod, använd detta idiom:
class C: @staticmethod def f(arg1, arg2, argN): ...
Formen
@staticmethodär en funktion decorator – se Function definitions för detaljer.En statisk metod kan anropas antingen på klassen (t.ex.
C.f()) eller på en instans (t.ex.C().f()). Dessutom är den statiska metoden descriptor också anropsbar, så den kan användas i klassdefinitionen (t.ex.f()).Statiska metoder i Python liknar dem som finns i Java eller C++. Se även
classmethod()för en variant som är användbar för att skapa alternativa klasskonstruktörer.Som alla dekoratorer är det också möjligt att anropa
staticmethodsom en vanlig funktion och göra något med dess resultat. Detta behövs i vissa fall där du behöver en referens till en funktion från en klass och du vill undvika den automatiska omvandlingen till instansmetod. För dessa fall, använd detta idiom:def regular_function(): ... class C: method = staticmethod(regular_function)
För mer information om statiska metoder, se The standard type hierarchy.
Förändrat i version 3.10: Statiska metoder ärver nu metodattributen (
__module__,__name__,__qualname__,__doc__och__annotations__), har ett nytt attribut__wrapped__och kan nu anropas som vanliga funktioner.
- class str(*, encoding='utf-8', errors='strict')
- class str(object)
- class str(object, encoding, errors='strict')
- class str(object, *, errors)
Returnerar en
str-version av object. Sestr()för detaljer.strär den inbyggda strängen class. För allmän information om strängar, se Text Sequence Type — str.
- sum(iterable, /, start=0)¶
Summerar start och posterna i en iterabel från vänster till höger och returnerar totalsumman. Posterna i iterabeln är normalt tal och startvärdet får inte vara en sträng.
För vissa användningsfall finns det bra alternativ till
sum(). Det föredragna, snabba sättet att sammanfoga en sekvens av strängar är genom att anropa''.join(sequence). För att lägga till flyttalsvärden med utökad precision, semath.fsum(). För att konkatenera en serie iterabler, överväg att användaitertools.chain().Förändrat i version 3.8: Parametern start kan anges som ett nyckelordsargument.
Förändrat i version 3.12: Summering av flyttal har bytts till en algoritm som ger högre noggrannhet och bättre kommutativitet på de flesta byggen.
Förändrat i version 3.14: Lagt till specialisering för summering av komplex, med samma algoritm som för summering av flyttal.
- class super¶
- class super(type, object_or_type=None, /)
Returnerar ett proxyobjekt som delegerar metodanrop till en överordnad eller syskonklass av typ. Detta är användbart för att komma åt ärvda metoder som har åsidosatts i en klass.
Object_or_type bestämmer vilken method resolution order som ska sökas. Sökningen börjar från klassen direkt efter typ.
Till exempel, om
__mro__av object_or_type ärD -> B -> C -> A -> objectoch värdet av type ärB, då sökersuper()C -> A -> object.Attributet
__mro__i den klass som motsvarar object_or_type listar den sökordning för metodupplösning som används av bådegetattr()ochsuper(). Attributet är dynamiskt och kan ändras när arvshierarkin uppdateras.Om det andra argumentet utelämnas är det superobjekt som returneras obundet. Om det andra argumentet är ett objekt måste
isinstance(obj, type)vara true. Om det andra argumentet är en typ måsteissubclass(type2, type)vara true (detta är användbart för classmethods).Vid anrop direkt inom en vanlig metod i en klass kan båda argumenten utelämnas (”zero-argument
super()”). I detta fall kommer type att vara den inneslutande klassen och obj kommer att vara det första argumentet i den omedelbart inneslutande funktionen (vanligtvisself). (Detta innebär att nollargumentetsuper()inte fungerar som förväntat inom nästlade funktioner, inklusive generatoruttryck, som implicit skapar nästlade funktioner)Det finns två typiska användningsområden för super. I en klasshierarki med enkel nedärvning kan super användas för att hänvisa till överordnade klasser utan att namnge dem explicit, vilket gör koden mer lätthanterlig. Denna användning är nära parallell med användningen av super i andra programmeringsspråk.
Det andra användningsfallet är att stödja kooperativ multipel nedärvning i en dynamisk exekveringsmiljö. Detta användningsfall är unikt för Python och finns inte i statiskt kompilerade språk eller språk som bara stöder enkel arvbarhet. Detta gör det möjligt att implementera ”diamantdiagram” där flera basklasser implementerar samma metod. God design kräver att sådana implementationer har samma anropssignatur i samtliga fall (eftersom anropsordningen bestäms vid körning, eftersom denna ordning anpassas till förändringar i klasshierarkin och eftersom denna ordning kan omfatta syskonklasser som är okända före körning).
För båda användningsfallen ser ett typiskt superklassanrop ut så här:
class C(B): def method(self, arg): super().method(arg) # This does the same thing as: # super(C, self).method(arg)
Förutom metoduppslagningar fungerar
super()också för attributuppslagningar. Ett möjligt användningsfall för detta är att anropa descriptors i en överordnad eller syskonklass.Observera att
super()implementeras som en del av bindningsprocessen för uttryckliga prickade attributuppslagningar somsuper().__getitem__(name). Den gör detta genom att implementera sin egen__getattribute__()-metod för att söka klasser i en förutsägbar ordning som stöder kooperativ multipel nedärvning. Följaktligen ärsuper()odefinierad för implicita uppslagningar med satser eller operatorer somsuper()[name].Observera också att
super(), bortsett från formen med noll argument, inte är begränsad till att användas inuti metoder. Formen med två argument specificerar argumenten exakt och gör lämpliga referenser. Formen med nollargument fungerar bara inuti en klassdefinition, eftersom kompilatorn fyller i de nödvändiga detaljerna för att korrekt hämta den klass som definieras, samt för att komma åt den aktuella instansen för vanliga metoder.För praktiska förslag på hur man utformar kooperativa klasser med hjälp av
super(), se guide to using super().Förändrat i version 3.14:
super-objekt är nupickleableochcopyable.
- class tuple(iterable=(), /)
I stället för att vara en funktion är
tuplefaktiskt en oföränderlig sekvenstyp, vilket dokumenteras i Tuples och Sekvenstyper — list, tuple, range.
- class type(object, /)¶
- class type(name, bases, dict, /, **kwargs)
Returnerar typen av ett objekt med ett argument. Returvärdet är ett typobjekt och i allmänhet samma objekt som returneras av
object.__class__.Den inbyggda funktionen
isinstance()rekommenderas för att testa typen av ett objekt, eftersom den tar hänsyn till underklasser.Med tre argument, returnerar ett nytt typobjekt. Detta är i huvudsak en dynamisk form av
class-satsen. Strängen name är klassnamnet och blir attributet__name__. Tupeln bases innehåller basklasserna och blir attributet__bases__; om den är tom läggsobject, den yttersta basen för alla klasser, till. Dictionariet dict innehåller attribut- och metoddefinitioner för klassens kropp; det kan kopieras eller omslutas innan det blir attributet__dict__. Följande två satser skapar identiskatype-objekt:>>> class X: ... a = 1 ... >>> X = type('X', (), dict(a=1))
Se även nedan:
Nyckelordsargument som anges i formuläret med tre argument skickas till lämplig metaklassmekanism (vanligtvis
__init_subclass__()) på samma sätt som nyckelord i en klassdefinition (förutom metaklass).Se även Customizing class creation.
Förändrat i version 3.6: Underklasser till
typesom inte åsidosättertype.__new__får inte längre använda ett-argument-formuläret för att få fram typen av ett objekt.
- vars()¶
- vars(object, /)
Returnerar attributet
__dict__för en modul, klass, instans eller något annat objekt med attributet__dict__.Objekt som moduler och instanser har ett uppdaterbart attribut
__dict__, men andra objekt kan ha skrivbegränsningar på sina attribut__dict__(klasser använder t.ex. entypes.MappingProxyTypeför att förhindra direkta uppdateringar av ordlistan).Utan ett argument fungerar
vars()somlocals().Ett undantag av typen
TypeErroruppstår om ett objekt anges men det inte har något attribut__dict__(t.ex. om dess klass definierar attributet__slots__).Förändrat i version 3.13: Resultatet av att anropa denna funktion utan ett argument har uppdaterats enligt beskrivningen för
locals()builtin.
- zip(*iterables, strict=False)¶
Iterera över flera iterabler parallellt och producera tuples med ett objekt från var och en.
Exempel:
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']): ... print(item) ... (1, 'sugar') (2, 'spice') (3, 'everything nice')
Mer formellt:
zip()returnerar en iterator av tupler, där den i:e tupeln innehåller det i:e elementet från var och en av argumentets iterabler.Ett annat sätt att tänka på
zip()är att den förvandlar rader till kolumner och kolumner till rader. Detta liknar transponering av en matris.zip()är lat: Elementen kommer inte att bearbetas förrän iterabeln itereras, t.ex. genom enfor-loop eller genom att packas in i enlist.En sak att tänka på är att de iterabler som skickas till
zip()kan ha olika längd; ibland på grund av design, och ibland på grund av en bugg i koden som förberedde dessa iterabler. Python erbjuder tre olika sätt att hantera detta problem:Som standard stoppar
zip()när den kortaste iterabeln är uttömd. Den ignorerar de återstående objekten i de längre iterationerna och skär av resultatet till längden på den kortaste iterationen:>>> list(zip(range(3), ['fee', 'fi', 'fo', 'fum'])) [(0, 'fee'), (1, 'fi'), (2, 'fo')]
zip()is often used in cases where the iterables are assumed to be of equal length. In such cases, it’s recommended to use thestrict=Trueoption. Its output is the same as regularzip():>>> list(zip(('a', 'b', 'c'), (1, 2, 3), strict=True)) [('a', 1), ('b', 2), ('c', 3)]
Unlike the default behavior, it raises a
ValueErrorif one iterable is exhausted before the others:>>> for item in zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True): ... print(item) ... (0, 'fee') (1, 'fi') (2, 'fo') Traceback (most recent call last): ... ValueError: zip() argument 2 is longer than argument 1
Without the
strict=Trueargument, any bug that results in iterables of different lengths will be silenced, possibly manifesting as a hard-to-find bug in another part of the program.Shorter iterables can be padded with a constant value to make all the iterables have the same length. This is done by
itertools.zip_longest().
Edge cases: With a single iterable argument,
zip()returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.Tips and tricks:
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using
zip(*[iter(s)]*n, strict=True). This repeats the same iteratorntimes so that each output tuple has the result ofncalls to the iterator. This has the effect of dividing the input into n-length chunks.zip()in conjunction with the*operator can be used to unzip a list:>>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> list(zip(x, y)) [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zip(x, y)) >>> x == list(x2) and y == list(y2) True
Förändrat i version 3.10: Added the
strictargument.
- __import__(name, globals=None, locals=None, fromlist=(), level=0)¶
Observera
This is an advanced function that is not needed in everyday Python programming, unlike
importlib.import_module().This function is invoked by the
importstatement. It can be replaced (by importing thebuiltinsmodule and assigning tobuiltins.__import__) in order to change semantics of theimportstatement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of__import__()is also discouraged in favor ofimportlib.import_module().The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all and uses its globals only to determine the package context of the
importstatement.level specifies whether to use absolute or relative imports.
0(the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling__import__()(see PEP 328 for the details).When the name variable is of the form
package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.For example, the statement
import spamresults in bytecode resembling the following code:spam = __import__('spam', globals(), locals(), [], 0)
The statement
import spam.hamresults in this call:spam = __import__('spam.ham', globals(), locals(), [], 0)
Note how
__import__()returns the toplevel module here because this is the object that is bound to a name by theimportstatement.On the other hand, the statement
from spam.ham import eggs, sausage as sausresults in_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage
Here, the
spam.hammodule is returned from__import__(). From this object, the names to import are retrieved and assigned to their respective names.If you simply want to import a module (potentially within a package) by name, use
importlib.import_module().Förändrat i version 3.3: Negative values for level are no longer supported (which also changes the default value to 0).
Förändrat i version 3.9: When the command line options
-Eor-Iare being used, the environment variablePYTHONCASEOKis now ignored.
Footnotes