Movatterモバイル変換


[0]ホーム

URL:


Navigation

Built-in Functions

The Python interpreter has a number of functions and types built into it thatare always available. They are listed here in alphabetical order.

abs(x)
Return the absolute value of a number. The argument may be aninteger or a floating point number. If the argument is a complex number, itsmagnitude is returned.
all(iterable)

Return True if all elements of theiterable are true. Equivalent to:

defall(iterable):forelementiniterable:ifnotelement:returnFalsereturnTrue
any(iterable)

Return True if any element of theiterable is true. Equivalent to:

defany(iterable):forelementiniterable:ifelement:returnTruereturnFalse
ascii(object)
Asrepr(), return a string containing a printable representation of anobject, but escape the non-ASCII characters in the string returned byrepr() using\x,\u or\U escapes. This generates a stringsimilar to that returned byrepr() in Python 2.
bin(x)
Convert an integer number to a binary string. The result is a valid Pythonexpression. Ifx is not a Pythonint object, it has to define an__index__() method that returns an integer.
bool([x])
Convert a value to a Boolean, using the standard truth testing procedure. Ifx is false or omitted, this returnsFalse; otherwise it returnsTrue.bool is also a class, which is a subclass ofint. Classbool cannot be subclassed further. Its onlyinstances areFalse andTrue.
bytearray([arg[,encoding[,errors]]])

Return a new array of bytes. Thebytearray type is a mutablesequence of integers in the range 0 <= x < 256. It has most of the usualmethods of mutable sequences, described inMutable Sequence Types, as wellas most methods that thestr type has, seeBytes and Byte Array Methods.

The optionalarg parameter can be used to initialize the array in a fewdifferent ways:

  • If it is astring, you must also give theencoding (and optionally,errors) parameters;bytearray() then converts the string tobytes usingstr.encode().
  • If it is aninteger, the array will have that size and will beinitialized with null bytes.
  • If it is an object conforming to thebuffer interface, a read-only bufferof the object will be used to initialize the bytes array.
  • If it is aniterable, it must be an iterable of integers in the range0<=x<256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

bytes([arg[,encoding[,errors]]])

Return a new “bytes” object, which is an immutable sequence of integers inthe range0<=x<256.bytes is an immutable version ofbytearray – it has the same non-mutating methods and the sameindexing and slicing behavior.

Accordingly, constructor arguments are interpreted as forbuffer().

Bytes objects can also be created with literals, seeString and Bytes literals.

chr(i)
Return the string of one character whose Unicode codepoint is the integeri. For example,chr(97) returns the string'a'. This is theinverse oford(). The valid range for the argument depends how Pythonwas configured – it may be either UCS2 [0..0xFFFF] or UCS4 [0..0x10FFFF].ValueError will be raised ifi is outside that range.
classmethod(function)

Return a class method forfunction.

A class method receives the class as implicit first argument, just like aninstance method receives the instance. To declare a class method, use thisidiom:

classC:@classmethoddeff(cls,arg1,arg2,...):...

The@classmethod form is a functiondecorator – see the descriptionof function definitions inFunction definitions for details.

It can be called either on the class (such asC.f()) or on an instance (suchasC().f()). The instance is ignored except for its class. If a classmethod is called for a derived class, the derived class object is passed as theimplied first argument.

Class methods are different than C++ or Java static methods. If you want those,seestaticmethod() in this section.

For more information on class methods, consult the documentation on the standardtype hierarchy inThe standard type hierarchy.

compile(source,filename,mode[,flags[,dont_inherit]])

Compile thesource into a code or AST object. Code objects can be executedby anexec statement or evaluated by a call toeval().source can either be a string or an AST object. Refer to theastmodule documentation for information on how to work with AST objects.

Thefilename argument should give the file from which the code was read;pass some recognizable value if it wasn’t read from a file ('<string>' iscommonly used).

Themode argument specifies what kind of code must be compiled; it can be'exec' ifsource consists of a sequence of statements,'eval' if itconsists of a single expression, or'single' if it consists of a singleinteractive statement (in the latter case, expression statements thatevaluate to something else thanNone will be printed).

The optional argumentsflags anddont_inherit control which futurestatements (seePEP 236) affect the compilation ofsource. If neitheris present (or both are zero) the code is compiled with those futurestatements that are in effect in the code that is calling compile. If theflags argument is given anddont_inherit is not (or is zero) then thefuture statements specified by theflags argument are used in addition tothose that would be used anyway. Ifdont_inherit is a non-zero integer thentheflags argument is it – the future statements in effect around the callto compile are ignored.

Future statements are specified by bits which can be bitwise ORed together tospecify multiple statements. The bitfield required to specify a given featurecan be found as thecompiler_flag attribute on the_Featureinstance in the__future__ module.

This function raisesSyntaxError if the compiled source is invalid,andTypeError if the source contains null bytes.

Note

When compiling a string with multi-line statements, line endings must berepresented by a single newline character ('\n'), and the input mustbe terminated by at least one newline character. If line endings arerepresented by'\r\n', usestr.replace() to change them into'\n'.

complex([real[,imag]])

Create a complex number with the valuereal +imag*j or convert a string ornumber to a complex number. If the first parameter is a string, it will beinterpreted as a complex number and the function must be called without a secondparameter. The second parameter can never be a string. Each argument may be anynumeric type (including complex). Ifimag is omitted, it defaults to zero andthe function serves as a numeric conversion function likeint()andfloat(). If both arguments are omitted, returns0j.

The complex type is described inNumeric Types — int, float, complex.

delattr(object,name)
This is a relative ofsetattr(). The arguments are an object and astring. The string must be the name of one of the object’s attributes. Thefunction deletes the named attribute, provided the object allows it. Forexample,delattr(x,'foobar') is equivalent todelx.foobar.
dict([arg])

Create a new data dictionary, optionally with items taken fromarg.The dictionary type is described inMapping Types — dict.

For other containers see the built inlist,set, andtuple classes, and thecollections module.

dir([object])

Without arguments, return the list of names in the current local scope. With anargument, attempt to return a list of valid attributes for that object.

If the object has a method named__dir__(), this method will be called andmust 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 togather information from the object’s__dict__ attribute, if defined, andfrom its type object. The resulting list is not necessarily complete, and maybe inaccurate when the object has a custom__getattr__().

The defaultdir() mechanism behaves differently with different types ofobjects, 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’sattributes.
  • If the object is a type or class object, the list contains the names of itsattributes, and recursively of the attributes of its bases.
  • Otherwise, the list contains the object’s attributes’ names, the names of itsclass’s attributes, and recursively of the attributes of its class’s baseclasses.

The resulting list is sorted alphabetically. For example:

>>>importstruct>>>dir()# doctest: +SKIP['__builtins__', '__doc__', '__name__', 'struct']>>>dir(struct)# doctest: +NORMALIZE_WHITESPACE['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from']>>>classFoo(object):...def__dir__(self):...return["kan","ga","roo"]...>>>f=Foo()>>>dir(f)['ga', 'kan', 'roo']

Note

Becausedir() is supplied primarily as a convenience for use at aninteractive prompt, it tries to supply an interesting set of names more than ittries to supply a rigorously or consistently defined set of names, and itsdetailed behavior may change across releases. For example, metaclass attributesare 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 numbersconsisting of their quotient and remainder when using integer division. With mixedoperand types, the rules for binary arithmetic operators apply. For integers,the result is the same as(a//b,a%b). For floating pointnumbers the result is(q,a%b), whereq is usuallymath.floor(a/b)but may be 1 less than that. In any caseq*b+a%b is very close toa, ifa%b is non-zero it has the same sign asb, and0<=abs(a%b)<abs(b).
enumerate(iterable[,start=0])

Return an enumerate object.iterable must be a sequence, aniterator, or some other object which supports iteration. The__next__() method of the iterator returned byenumerate() returns atuple containing a count (fromstart which defaults to 0) and thecorresponding value obtained from iterating overiterable.enumerate() is useful for obtaining an indexed series:(0,seq[0]),(1,seq[1]),(2,seq[2]), .... For example:

>>>fori,seasoninenumerate(['Spring','Summer','Fall','Winter']):...print(i,season)0 Spring1 Summer2 Fall3 Winter
eval(expression[,globals[,locals]])

The arguments are a string and optional globals and locals. If provided,globals must be a dictionary. If provided,locals can be any mappingobject.

Theexpression argument is parsed and evaluated as a Python expression(technically speaking, a condition list) using theglobals andlocalsdictionaries as global and local namespace. If theglobals dictionary ispresent and lacks ‘__builtins__’, the current globals are copied intoglobalsbeforeexpression is parsed. This means thatexpression normally has fullaccess to the standardbuiltins module and restricted environments arepropagated. If thelocals dictionary is omitted it defaults to theglobalsdictionary. If both dictionaries are omitted, the expression is executed in theenvironment whereeval() is called. The return value is the result ofthe evaluated expression. Syntax errors are reported as exceptions. Example:

>>>x=1>>>eval('x+1')2

This function can also be used to execute arbitrary code objects (such asthose created bycompile()). In this case pass a code object insteadof a string. If the code object has been compiled with'exec' as thekind argument,eval()‘s return value will beNone.

Hints: dynamic execution of statements is supported by theexec()function. Theglobals() andlocals() functionsreturns the current global and local dictionary, respectively, which may beuseful to pass around for use byeval() orexec().

exec(object[,globals[,locals]])

This function supports dynamic execution of Python code.object must beeither a string or a code object. If it is a string, the string is parsed asa suite of Python statements which is then executed (unless a syntax erroroccurs). If it is a code object, it is simply executed. In all cases, thecode that’s executed is expected to be valid as file input (see the section“File input” in the Reference Manual). Be aware that thereturnandyield statements may not be used outside of functiondefinitions 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 thecurrent scope. If onlyglobals is provided, it must be a dictionary, whichwill be used for both the global and the local variables. Ifglobals andlocals are given, they are used for the global and local variables,respectively. If provided,locals can be any mapping object.

If theglobals dictionary does not contain a value for the key__builtins__, a reference to the dictionary of the built-in modulebuiltins is inserted under that key. That way you can control whatbuiltins are available to the executed code by inserting your own__builtins__ dictionary intoglobals before passing it toexec().

Note

The built-in functionsglobals() andlocals() return the currentglobal and local dictionary, respectively, which may be useful to pass aroundfor use as the second and third argument toexec().

Warning

The defaultlocals act as described for functionlocals() below:modifications to the defaultlocals dictionary should not be attempted.Pass an explicitlocals dictionary if you need to see effects of thecode onlocals after functionexec() returns.

filter(function,iterable)

Construct an iterator from those elements ofiterable for whichfunctionreturns true.iterable may be either a sequence, a container whichsupports iteration, or an iterator. Iffunction isNone, the identityfunction is assumed, that is, all elements ofiterable that are false areremoved.

Note thatfilter(function,iterable) is equivalent to the generatorexpression(itemforiteminiterableiffunction(item)) if function isnotNone and(itemforiteminiterableifitem) if function isNone.

float([x])

Convert a string or a number to floating point. If the argument is a string,it must contain a possibly signed decimal or floating point number, possiblyembedded in whitespace. The argument may also be'[+|-]nan' or'[+|-]inf'. Otherwise, the argument may be an integer or a floatingpoint number, and a floating point number with the same value (withinPython’s floating point precision) is returned. If no argument is given,0.0 is returned.

Note

When passing in a string, values for NaN and Infinity may be returned,depending on the underlying C library. Float accepts the strings'nan','inf' and'-inf' for NaN and positive or negativeinfinity. The case and a leading + are ignored as well as a leading - isignored for NaN. Float always represents NaN and infinity asnan,inf or-inf.

The float type is described inNumeric Types — int, float, complex.

format(value[,format_spec])

Convert a string or a number to a “formatted” representation, as controlledbyformat_spec. The interpretation offormat_spec will depend on thetype of thevalue argument, however there is a standard formatting syntaxthat is used by most built-in types:Format Specification Mini-Language.

Note

format(value,format_spec) merely callsvalue.__format__(format_spec).

frozenset([iterable])

Return a frozenset object, optionally with elements taken fromiterable.The frozenset type is described inSet Types — set, frozenset.

For other containers see the built indict,list, andtuple classes, and thecollections module.

getattr(object,name[,default])
Return the value of the named attributed ofobject.name must be a string.If the string is the name of one of the object’s attributes, the result is thevalue of that attribute. For example,getattr(x,'foobar') is equivalent tox.foobar. If the named attribute does not exist,default is returned ifprovided, otherwiseAttributeError is raised.
globals()
Return a dictionary representing the current global symbol table. This is alwaysthe dictionary of the current module (inside a function or method, this is themodule where it is defined, not the module from which it is called).
hasattr(object,name)
The arguments are an object and a string. The result isTrue if the stringis the name of one of the object’s attributes,False if not. (This isimplemented by callinggetattr(object,name) and seeing whether it raises anexception or 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 ofdifferent types, as is the case for 1 and 1.0).
help([object])

Invoke the built-in help system. (This function is intended for interactiveuse.) If no argument is given, the interactive help system starts on theinterpreter console. If the argument is a string, then the string is looked upas the name of a module, function, class, method, keyword, or documentationtopic, and a help page is printed on the console. If the argument is any otherkind of object, a help page on the object is generated.

This function is added to the built-in namespace by thesite module.

hex(x)
Convert an integer number to a hexadecimal string. The result is a valid Pythonexpression. Ifx is not a Pythonint object, it has to define an__index__() method that returns an integer.
id(object)
Return the “identity” of an object. This is an integer whichis guaranteed to be unique and constant for this object during its lifetime.Two objects with non-overlapping lifetimes may have the sameid() value.(Implementation note: this is the address of the object.)
input([prompt])

If theprompt argument is present, it is written to standard output withouta trailing newline. The function then reads a line from input, converts itto a string (stripping a trailing newline), and returns that. When EOF isread,EOFError is raised. Example:

>>>s=input('--> ')--> Monty Python's Flying Circus>>>s"Monty Python's Flying Circus"

If thereadline module was loaded, theninput() will use itto provide elaborate line editing and history features.

int([number | string[,radix]])

Convert a number or string to an integer. If no arguments are given, return0. If a number is given, returnnumber.__int__(). Conversion offloating point numbers to integers truncates towards zero. A string must bea base-radix integer literal optionally preceded by ‘+’ or ‘-‘ (with no spacein between) and optionally surrounded by whitespace. A base-n literalconsists of the digits 0 to n-1, with ‘a’ to ‘z’ (or ‘A’ to ‘Z’) havingvalues 10 to 35. The default radix is 10. The allowed values are 0 and 2-36.Base-2, -8, and -16 literals can be optionally prefixed with0b/0B,0o/0O, or0x/0X, as with integer literals in code. Radix 0means to interpret exactly as a code literal, so that the actual radix is 2,8, 10, or 16, and so thatint('010',0) is not legal, whileint('010') is, as well asint('010',8).

The integer type is described inNumeric Types — int, float, complex.

isinstance(object,classinfo)
Return true if theobject argument is an instance of theclassinfoargument, or of a (direct or indirect) subclass thereof. Ifobject is notan object of the given type, the function always returns false. Ifclassinfo is not a class (type object), it may be a tuple of type objects,or may recursively contain other such tuples (other sequence types are notaccepted). Ifclassinfo is not a type or tuple of types and such tuples,aTypeError exception is raised.
issubclass(class,classinfo)
Return true ifclass is a subclass (direct or indirect) ofclassinfo. Aclass is considered a subclass of itself.classinfo may be a tuple of classobjects, in which case every entry inclassinfo will be checked. In any othercase, aTypeError exception is raised.
iter(o[,sentinel])
Return aniterator object. The first argument is interpreted very differentlydepending on the presence of the second argument. Without a second argument,omust be a collection object which supports the iteration protocol (the__iter__() method), or it must support the sequence protocol (the__getitem__() method with integer arguments starting at0). If itdoes not support either of those protocols,TypeError is raised. If thesecond argument,sentinel, is given, theno must be a callable object. Theiterator created in this case will callo with no arguments for each call toits__next__() method; if the value returned is equal tosentinel,StopIteration will be raised, otherwise the value will be returned.
len(s)
Return the length (the number of items) of an object. The argument may be asequence (string, tuple or list) or a mapping (dictionary).
list([iterable])

Return a list whose items are the same and in the same order asiterable‘sitems.iterable may be either a sequence, a container that supportsiteration, or an iterator object. Ifiterable is already a list, a copy ismade and returned, similar toiterable[:]. For instance,list('abc')returns['a','b','c'] andlist((1,2,3)) returns[1,2,3]. Ifno argument is given, returns a new empty list,[].

list is a mutable sequence type, as documented inSequence Types — str, bytes, bytearray, list, tuple, range.

locals()

Update and return a dictionary representing the current local symbol table.

Warning

The contents of this dictionary should not be modified; changes may not affectthe values of local variables used by the interpreter.

Free variables are returned bylocals() when it is called in a function block.Modifications of free variables may not affect the values used by theinterpreter. Free variables are not returned in class blocks.

map(function,iterable,...)
Return an iterator that appliesfunction to every item ofiterable,yielding the results. If additionaliterable arguments are passed,function must take that many arguments and is applied to the items from alliterables in parallel. With multiple iterables, the iterator stops when theshortest iterable is exhausted.
max(iterable[,args...],*[,key])

With a single argumentiterable, return the largest item of a non-emptyiterable (such as a string, tuple or list). With more than one argument, returnthe largest of the arguments.

The optional keyword-onlykey argument specifies a one-argument orderingfunction like that used forlist.sort().

memoryview(obj)
Return a “memory view” object created from the given argument. Seememoryview Types for more information.
min(iterable[,args...],*[,key])

With a single argumentiterable, return the smallest item of a non-emptyiterable (such as a string, tuple or list). With more than one argument, returnthe smallest of the arguments.

The optional keyword-onlykey argument specifies a one-argument orderingfunction like that used forlist.sort().

next(iterator[,default])
Retrieve the next item from theiterator by calling its__next__()method. Ifdefault is given, it is returned if the iterator is exhausted,otherwiseStopIteration is raised.
object()

Return a new featureless object.object is a base for all classes.It has the methods that are common to all instances of Python classes. Thisfunction does not accept any arguments.

Note

object doesnot have a__dict__, so you can’t assignarbitrary attributes to an instance of theobject class.

oct(x)
Convert an integer number to an octal string. The result is a valid Pythonexpression. Ifx is not a Pythonint object, it has to define an__index__() method that returns an integer.
open(file[,mode='r'[,buffering=None[,encoding=None[,errors=None[,newline=None[,closefd=True]]]]]])

Open a file. If the file cannot be opened,IOError is raised.

file is either a string or bytes object giving the name (and the path ifthe file isn’t in the current working directory) of the file to be opened oran integer file descriptor of the file to be wrapped. (If a file descriptoris given, it is closed when the returned I/O object is closed, unlessclosefd is set toFalse.)

mode is an optional string that specifies the mode in which the file isopened. It defaults to'r' which means open for reading in text mode.Other common values are'w' for writing (truncating the file if italready exists), and'a' for appending (which onsome Unix systems,means thatall writes append to the end of the file regardless of thecurrent seek position). In text mode, ifencoding is not specified theencoding used is platform dependent. (For reading and writing raw bytes usebinary mode and leaveencoding unspecified.) The available modes are:

CharacterMeaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open a disk file for updating (reading and writing)
'U'universal newline mode (for backwards compatibility; unneededfor new code)

The default mode is'rt' (open for reading text). For binary randomaccess, the mode'w+b' opens and truncates the file to 0 bytes, while'r+b' opens the file without truncation.

Python distinguishes between files opened in binary and text modes, evenwhen the underlying operating system doesn’t. Files opened in binarymode (appending'b' to themode argument) return contents asbytes objects without any decoding. In text mode (the default, or when't' is appended to themode argument) the contents ofthe file are returned as strings, the bytes having been first decodedusing a platform-dependent encoding or using the specifiedencodingif given.

buffering is an optional integer used to set the buffering policy. Bydefault full buffering is on. Pass 0 to switch buffering off (only allowed inbinary mode), 1 to set line buffering, and an integer > 1 for full buffering.

encoding is the name of the encoding used to decode or encode the file.This should only be used in text mode. The default encoding is platformdependent, but any encoding supported by Python can be passed. See thecodecs module for the list of supported encodings.

errors is an optional string that specifies how encoding errors are to behandled—this argument should not be used in binary mode. Pass'strict'to raise aValueError exception if there is an encoding error (thedefault ofNone has the same effect), or pass'ignore' to ignoreerrors. (Note that ignoring encoding errors can lead to data loss.) See thedocumentation forcodecs.register() for a list of the permittedencoding error strings.

newline controls how universal newlines works (it only applies to textmode). It can beNone,'','\n','\r', and'\r\n'. Itworks as follows:

  • On input, ifnewline isNone, universal newlines mode is enabled.Lines in the input can end in'\n','\r', or'\r\n', and theseare translated into'\n' before being returned to the caller. If it is'', universal newline mode is enabled, but line endings are returned tothe caller untranslated. If it has any of the other legal values, inputlines are only terminated by the given string, and the line ending isreturned to the caller untranslated.
  • On output, ifnewline isNone, any'\n' characters written aretranslated to the system default line separator,os.linesep. Ifnewline is'', no translation takes place. Ifnewline is any ofthe other legal values, any'\n' characters written are translated tothe given string.

Ifclosefd isFalse, the underlying file descriptor will be kept openwhen the file is closed. This does not work when a file name is given andmust beTrue in that case.

See also the file handling modules, such as,fileinput,io(whereopen() is declared),os,os.path,tempfile, andshutil.

ord(c)

Given a string of length one, return an integer representing the Unicode codepoint of the character. For example,ord('a') returns the integer97andord('\u2020') returns8224. This is the inverse ofchr().

If the argument length is not one, aTypeError will be raised. (IfPython was built with UCS2 Unicode, then the character’s code point must bein the range [0..65535] inclusive; otherwise the string length is two!)

pow(x,y[,z])

Returnx to the powery; ifz is present, returnx to the powery,moduloz (computed more efficiently thanpow(x,y)%z). The two-argumentformpow(x,y) is equivalent to using the power operator:x**y.

The arguments must have numeric types. With mixed operand types, thecoercion rules for binary arithmetic operators apply. Forintoperands, the result has the same type as the operands (after coercion)unless the second argument is negative; in that case, all arguments areconverted to float and a float result is delivered. For example,10**2returns100, but10**-2 returns0.01. If the second argument isnegative, the third argument must be omitted. Ifz is present,x andymust be of integer types, andy must be non-negative.

print([object,...][,sep=' '][,end='\n'][,file=sys.stdout])

Printobject(s) to the streamfile, separated bysep and followed byend.sep,end andfile, if present, must be given as keywordarguments.

All non-keyword arguments are converted to strings likestr() does andwritten to the stream, separated bysep and followed byend. Bothsepandend must be strings; they can also beNone, which means to use thedefault values. If noobject is given,print() will just writeend.

Thefile argument must be an object with awrite(string) method; if itis not present orNone,sys.stdout will be used.

property([fget[,fset[,fdel[,doc]]]])

Return a property attribute.

fget is a function for getting an attribute value, likewisefset is afunction for setting, andfdel a function for del’ing, an attribute. Typicaluse is to define a managed attribute x:

class C(object):    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.")

If given,doc will be the docstring of the property attribute. Otherwise, theproperty will copyfget‘s docstring (if it exists). This makes it possible tocreate read-only properties easily usingproperty() as adecorator:

class Parrot(object):    def __init__(self):        self._voltage = 100000    @property    def voltage(self):        """Get the current voltage."""        return self._voltage

turns thevoltage() method into a “getter” for a read-only attributewith the same name.

A property object hasgetter,setter, anddeletermethods usable as decorators that create a copy of the property with thecorresponding accessor function set to the decorated function. This isbest explained with an example:

class C(object):    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

This code is exactly equivalent to the first example. Be sure to give theadditional functions the same name as the original property (x in thiscase.)

The returned property also has the attributesfget,fset, andfdel corresponding to the constructor arguments.

range([start],stop[,step])

This is a versatile function to create iterables yielding arithmeticprogressions. It is most often used infor loops. The argumentsmust be integers. If thestep argument is omitted, it defaults to1.If thestart argument is omitted, it defaults to0. The full formreturns an iterable of integers[start,start+step,start+2*step,...]. Ifstep is positive, the last element is the largeststart+i*step less thanstop; ifstep is negative, the last element is thesmalleststart+i*step greater thanstop.step must not be zero(or elseValueError is raised). Example:

>>>list(range(10))[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>>list(range(1,11))[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>>list(range(0,30,5))[0, 5, 10, 15, 20, 25]>>>list(range(0,10,3))[0, 3, 6, 9]>>>list(range(0,-10,-1))[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]>>>list(range(0))[]>>>list(range(1,0))[]
repr(object)
Return a string containing a printable representation of an object. For manytypes, this function makes an attempt to return a string that would yield anobject with the same value when passed toeval(), otherwise therepresentation is a string enclosed in angle brackets that contains the nameof the type of the object together with additional information oftenincluding the name and address of the object. A class can control what thisfunction returns for its instances by defining a__repr__() method.
reversed(seq)
Return a reverseiterator.seq must be an object which hasa__reversed__() method or supports the sequence protocol (the__len__() method and the__getitem__() method with integerarguments starting at0).
round(x[,n])

Return the floating point valuex rounded ton digits after the decimalpoint. Ifn is omitted, it defaults to zero. Delegates tox.__round__(n).

For the built-in types supportinground(), values are rounded to theclosest multiple of 10 to the power minusn; if two multiples are equallyclose, rounding is done toward the even choice (so, for example, bothround(0.5) andround(-0.5) are0, andround(1.5) is2).The return value is an integer if called with one argument, otherwise of thesame type asx.

set([iterable])
Return a new set, optionally with elements are taken fromiterable.The set type is described inSet Types — set, frozenset.
setattr(object,name,value)
This is the counterpart ofgetattr(). The arguments are an object, astring and an arbitrary value. The string may name an existing attribute or anew attribute. The function assigns the value to the attribute, provided theobject allows it. For example,setattr(x,'foobar',123) is equivalent tox.foobar=123.
slice([start],stop[,step])

Return aslice object representing the set of indices specified byrange(start,stop,step). Thestart andstep arguments default toNone. Slice objects have read-only data attributesstart,stop andstep which merely return the argument values (or theirdefault). They have no other explicit functionality; however they are used byNumerical Python and other third party extensions. Slice objects are alsogenerated when extended indexing syntax is used. For example:a[start:stop:step] ora[start:stop,i].

sorted(iterable[,key[,reverse]])

Return a new sorted list from the items initerable.

Has two optional arguments which must be specified as keyword arguments.

key specifies a function of one argument that is used to extract a comparisonkey from each list element:key=str.lower. The default value isNone.

reverse is a boolean value. If set toTrue, then the list elements aresorted as if each comparison were reversed.

staticmethod(function)

Return a static method forfunction.

A static method does not receive an implicit first argument. To declare a staticmethod, use this idiom:

classC:@staticmethoddeff(arg1,arg2,...):...

The@staticmethod form is a functiondecorator – see thedescription of function definitions inFunction definitions for details.

It can be called either on the class (such asC.f()) or on an instance (suchasC().f()). The instance is ignored except for its class.

Static methods in Python are similar to those found in Java or C++. For a moreadvanced concept, seeclassmethod() in this section.

For more information on static methods, consult the documentation on thestandard type hierarchy inThe standard type hierarchy.

str([object[,encoding[,errors]]])

Return a string version of an object, using one of the following modes:

Ifencoding and/orerrors are given,str() will decode theobject which can either be a byte string or a character buffer usingthe codec forencoding. Theencoding parameter is a string givingthe name of an encoding; if the encoding is not known,LookupErroris raised. Error handling is done according toerrors; this specifies thetreatment of characters which are invalid in the input encoding. Iferrors is'strict' (the default), aValueError is raised onerrors, while a value of'ignore' causes errors to be silently ignored,and a value of'replace' causes the official Unicode replacement character,U+FFFD, to be used to replace input characters which cannot be decoded.See also thecodecs module.

When onlyobject is given, this returns its nicely printable representation.For strings, this is the string itself. The difference withrepr(object)is thatstr(object) does not always attempt to return a string that isacceptable toeval(); its goal is to return a printable string.With no arguments, this returns the empty string.

Objects can specify whatstr(object) returns by defining a__str__()special method.

For more information on strings seeSequence Types — str, bytes, bytearray, list, tuple, range which describes sequencefunctionality (strings are sequences), and also the string-specific methodsdescribed in theString Methods section. To output formatted strings,see theString Formatting section. In addition see theString Services section.

sum(iterable[,start])
Sumsstart and the items of aniterable from left to right and returns thetotal.start defaults to0. Theiterable‘s items are normally numbers,and are not allowed to be strings. The fast, correct way to concatenate asequence of strings is by calling''.join(sequence).
super([type[,object-or-type]])

Return asuper object that acts as a proxy to superclasses oftype.

If the second argument is omitted the super object returned is unbound. Ifthe second argument is an object,isinstance(obj,type) must be true. Ifthe second argument is a type,issubclass(type2,type) must be true.Callingsuper() without arguments is equivalent tosuper(this_class,first_arg).

There are two typical use cases forsuper(). In a class hierarchy withsingle inheritance,super() can be used to refer to parent classes withoutnaming them explicitly, thus making the code more maintainable. This useclosely parallels the use of “super” in other programming languages.

The second use case is to support cooperative multiple inheritence in adynamic execution environment. This use case is unique to Python and isnot found in statically compiled languages or languages that only supportsingle inheritance. This makes in possible to implement “diamond diagrams”where multiple base classes implement the same method. Good design dictatesthat this method have the same calling signature in every case (because theorder of parent calls is determined at runtime and because that order adaptsto changes in the class hierarchy).

For both use cases, a typical superclass call looks like this:

classC(B):defmethod(self,arg):super().method(arg)# This does the same thing as: super(C, self).method(arg)

Note thatsuper() is implemented as part of the binding process forexplicit dotted attribute lookups such assuper().__getitem__(name).It does so by implementing its own__getattribute__() method for searchingparent classes in a predictable order that supports cooperative multiple inheritance.Accordingly,super() is undefined for implicit lookups using statements oroperators such assuper()[name].

Also note thatsuper() is not limited to use inside methods. Thetwo argument specifies the arguments exactly and makes the appropriatereferences. The zero argument form automatically searches the stack framefor the class (__class__) and the first argument.

tuple([iterable])

Return a tuple whose items are the same and in the same order asiterable‘sitems.iterable may be a sequence, a container that supports iteration, or aniterator object. Ifiterable is already a tuple, it is returned unchanged.For instance,tuple('abc') returns('a','b','c') andtuple([1,2,3]) returns(1,2,3). If no argument is given, returns a new emptytuple,().

tuple is an immutable sequence type, as documented inSequence Types — str, bytes, bytearray, list, tuple, range.

type(object)

Return the type of anobject. The return value is a type object andgenerally the same object as returned byobject.__class__.

Theisinstance() built-in function is recommended for testing the typeof an object, because it takes subclasses into account.

With three arguments,type() functions as a constructor as detailedbelow.

type(name,bases,dict)

Return a new type object. This is essentially a dynamic form of theclass statement. Thename string is the class name and becomes the__name__ attribute; thebases tuple itemizes the base classes andbecomes the__bases__ attribute; and thedict dictionary is thenamespace containing definitions for class body and becomes the__dict__attribute. For example, the following two statements create identicaltype objects:

>>>classX(object):...a=1...>>>X=type('X',(object,),dict(a=1))
vars([object])
Without arguments, return a dictionary corresponding to the current local symboltable. With a module, class or class instance object as argument (or anythingelse that has a__dict__ attribute), returns a dictionary correspondingto the object’s symbol table. The returned dictionary should not be modified:the effects on the corresponding symbol table are undefined.[1]
zip(*iterables)

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where thei-th tuple containsthei-th element from each of the argument sequences or iterables. Theiterator stops when the shortest input iterable is exhausted. With a singleiterable argument, it returns an iterator of 1-tuples. With no arguments,it returns an empty iterator. Equivalent to:

defzip(*iterables):# zip('ABCD', 'xy') --> Ax Byiterables=map(iter,iterables)whileiterables:result=[it.next()foritiniterables]yieldtuple(result)

The left-to-right evaluation order of the iterables is guaranteed. Thismakes possible an idiom for clustering a data series into n-length groupsusingzip(*[iter(s)]*n).

zip() should only be used with unequal length inputs when you don’tcare about trailing, unmatched values from the longer iterables. If thosevalues are important, useitertools.zip_longest() instead.

zip() in conjunction with the* operator can be used to unzip alist:

>>>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==x2,y==y2True
__import__(name[,globals[,locals[,fromlist[,level]]]])

Note

This is an advanced function that is not needed in everyday Pythonprogramming.

This function is invoked by theimport statement. It can bereplaced (by importing thebuiltins module and assigning tobuiltins.__import__) in order to change semantics of theimport statement, but nowadays it is usually simpler to use importhooks (seePEP 302). Direct use of__import__() is rare, except incases where you want to import a module whose name is only known at runtime.

The function imports the modulename, potentially using the givenglobalsandlocals to determine how to interpret the name in a package context.Thefromlist gives the names of objects or submodules that should beimported from the module given byname. The standard implementation doesnot use itslocals argument at all, and uses itsglobals only todetermine the package context of theimport statement.

level specifies whether to use absolute or relative imports. The defaultis-1 which indicates both absolute and relative imports will beattempted.0 means only perform absolute imports. Positive values forlevel indicate the number of parent directories to search relative to thedirectory of the module calling__import__().

When thename variable is of the formpackage.module, normally, thetop-level package (the name up till the first dot) is returned,not themodule named byname. However, when a non-emptyfromlist argument isgiven, the module named byname is returned.

For example, the statementimportspam results in bytecode resembling thefollowing code:

spam=__import__('spam',globals(),locals(),[],-1)

The statementimportspam.ham results in this call:

spam=__import__('spam.ham',globals(),locals(),[],-1)

Note how__import__() returns the toplevel module here because this isthe object that is bound to a name by theimport statement.

On the other hand, the statementfromspam.hamimporteggs,sausageassaus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)eggs = _temp.eggssaus = _temp.sausage

Here, thespam.ham module is returned from__import__(). From thisobject, the names to import are retrieved and assigned to their respectivenames.

If you simply want to import a module (potentially within a package) by name,you can get it fromsys.modules:

>>>importsys>>>name='foo.bar.baz'>>>__import__(name)<module 'foo' from ...>>>>baz=sys.modules[name]>>>baz<module 'foo.bar.baz' from ...>

Footnotes

[1]Specifying a buffer size currently has no effect on systems that don’t havesetvbuf. The interface to specify the buffer size is not done using amethod that callssetvbuf, because that may dump core when called afterany I/O has been performed, and there’s no reliable way to determine whetherthis is the case.
[2]In the current implementation, local variable bindings cannot normally beaffected this way, but variables retrieved from other scopes (such as modules)can be. This may change.

Previous topic

Introduction

Next topic

Built-in Constants

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2009, Python Software Foundation. Last updated on Feb 14, 2009. Created usingSphinx 0.6.

[8]ページ先頭

©2009-2025 Movatter.jp