python--built-in types

Source: Internet
Author: User

Python defines a rich range of data types, including:

Numeric type: int, float, complex

Sequence: (iterable) str, Unicode, tuple, list, ByteArray, buffer, xrange

Set: Set, Fronzeset

Mapping: Dict

Files: File

Boolean: True, False, and bool () functions, where the bool () function converts a value to a Boolean object True or False.

Callable object: An object x that can call X (), called a callable, X can be a type, a function, an instance of the __call__ () method defined in a type, and so on.

None:

The Memoryview:memoryview object is a new object in Python2.7 that allows Python code to access an object that supports the Buffer Protocol (Protocol) its internal data, You can then turn it into a byte string or a list of characters that correspond to ASCII values, and so on.

  Context Manager: Context Manager in the WITH statement, the context Management protocol includes ContextManager. __enter__() and ContextManager. __exit__(Exc_type, Exc_val, EXC_TB) two methods.

Other:

In Python, modules, types, functions, instances, and objects are all objects, and in addition, there is a code object, which is the type object that an object belongs to, and is obtained through the type () function;

Type

Name Construction method Introduced

Basestring

Abstract (not instantiated) types, which are base types of STR and Unicode types, can be determined by isinstance (x, basestring) that x is not a str or Unicode type.
bool BOOL (x)

Used to evaluate the expression x and return whether X is true or false. BOOL is a subclass of int, with only two instances: the values of true and False,true and False are 1 and 0, respectively, but the values of STR (TRUE) and Str (false) are ' true ' and ' false ' respectively.

Buffer Buffer (obj, offset=0, size=-1)

obj must be a string or an array that returns a partially read-only Buffer object , starting with offset, size obj, if size<0, or obj is smaller than size, The end of obj is directly from offset.

Classmethod Class method Classmethod (function)

Returns a class method that can be used only in the definition of a class, with @classmethod instead.

Code Code Object Compile (source, filename, mode[, flags[, Dont_inherit]])

The code object is typically created by using the built-in function compile () method, or it can be viewed through the Func_code property of a function, as described below in detail on the code object.

Complex Plural Complex (real, imag=0)

Dict Dictionary Dict (x={})

If the parameter x is a dictionary, then a copy of it is returned, and the parameter x can also be an iterative object, where each element is a two-tuple, such as: x = [(' A ', 1), (' B ', 2)]

Enumerate Enumeration Enumerate (iterable, start=0)

A new iterator is generated from an iterative object, and each item of the iterator is a two-tuple, the first element of the two-tuple is a continuous increment from start, and the dimensions of the two-tuple is the inner element from which the parameter iterates the object from the beginning.

Open File Open (filename, mode= ' R ', Bufferzies=-1)

Opens the specified filename in the form of a parameter mode, returning a file object.

Float Floating point Type Float (x)

Converts a number or a suitable string into a floating point.

Frozenset Frozenset (seq=[])

Returns a Frozen collection object, see this blog post for a discussion of set and Frozenset.

Int Integral type Int (x[, radix])

Converts a number or an appropriate string into an integer, when x is a string, radix needs to be specified, representing the cardinality at the time of conversion, the default is 10, and the conversion cardinality can actually be between 2 and 36

List List List (seq=[])

If the parameter seq is a list, the copy of it is returned; the parameter seq must be an iterative object, and the list () return and the iterator object have the same sequence of elements in the same order.

Long Long integer type Long (x [, Radix])

Converts a number or appropriate string into a growing integer

Object Object ()

Returns a new instance of the most basic type.

Property Property Property (Fget=none, Fset=none, Fdel=none, Doc=none) Can only be used in class definitions, typically using adorners @property
Reversed Reversed (SEQ)

Returns an iterator that has the opposite element object for this iterator and sequence seq, which does not change the parameter seq

Set Collection Set (seq=[])

Returns a set object, the Set object is mutable , if SEQ is a set object, then set (SEQ) returns its copy, and a detailed discussion of the built-in type set and Frozenset reference to this blog post

Slice Slice Slice ([Start,] stop[, step])

Returns a Slice object,

Staticmethod Static methods Staticmethod (function) Called only in the class definition, returns a static method object, or uses the adorner @staticmethod
Str Plain string STR (obj)

If obj is itself a str type, the Obj object is returned; otherwise, the reader-oriented form of the Obj object is returned, mainly in the form of the repr-oriented Python interpreter

Super Super (CLS, obj)

Returns the object of the parent class of the parameter obj, which must be an instance of the CLS or CLS subclass, which is primarily used to invoke the method of the parent class, which is called only in the method code

Tuple Meta-group Tuple (SEQ)

If the SEQ is a tuple object, returns a copy of it, otherwise, returns a tuple object that has the same order as the SEQ, and the SEQ must be an iterative object

Type Type (obj)

Type (x) is equivalent to x.__class__, which is the type object to which x belongs.

The type itself is a built-in, or can be used as a factory object, returning a type object. Type objects in Python can only be compared (equality comparison) and string representations that support equality or not.

Object-oriented, type objects are often callable, such as built-in int, float, list, and so on, calling these objects to create their instances, while type objects can be inherited (subclass), which are the basic characteristics of the type.

Unicode Unicode string Unicode (string [, codec, [, errors]]) Returns a Unicode string object
Xrange Xrange ([Start,] stop [, Step=1])

Range () Returns a list object, and Xrange () returns an iterative xrange object that does not generate all the elements in memory like the list returned by range (). Instead, each time one is generated during the iteration, the xrange has a significant advantage in memory for traversing the digital sequence of large data volumes. After Python 3, the concept of xrange is no longer used, but the range is improved based on the xrange in Python 2, making the range in Python 3 more powerful.

The code object in Python

Let's first look at the introduction of the built-in function compile ():

Compile (source, filename, mode[, flags[, Dont_inherit])code objectcompile The source string (a Python module, statementorexpression) into a code object the can is executed by theexecStatementoreval (). The filename would be used forrun-Time error messages. The mode must be'exec'To compile a module,' Single'to compile a single (interactive) statement,or 'Eval'To compile an expression. The flags argument,ifpresent, controls which future statements influence the compilation of the code. The Dont_inherit argument,ifNon-zero, stops the compilation inheriting the effects of any future statementsinchEffectinchThe code calling compile;ifAbsentorZero these statements do influence the compilation,inchaddition to any features explicitly specified.

To sum up is:

The compile () function is used to construct a code object that can be used as an argument to exec () and eval ();

For any Python function, its Func_code property is a code object that is not callable, but can be bound to another function object with the same number of arguments , creating a new Function object:

>>> f = lambda x, y:x + y>>> F.func_code<code object <lambda> at 0000000001d74530, file "<s Tdin> ", line 1>>>> code_obj = f.func_code>>> def g (x, y): pass...>>> G.func_code = code_o Bj>>> g (1, 9) 10

Originally we did not define function g function body, but by replacing its Func_code property, you can replace the non-callable code object into a callable function, is there a sense of jinchantuoqiao?

Python's Types module

The properties of the types module are the built-in types of Python, including:

>>> dir (types) [' Booleantype ', ' buffertype ', ' builtinfunctiontype ', ' builtinmethodtype ', ' ClassType ', ' CodeType ', ' ComplexType ', ' dictproxytype ', ' dicttype ', ' dictionarytype ', ' ellipsistype ', ' FileType ', ' floattype ', ' Frametype ', ' functiontype ', ' generatortype ', ' getsetdescriptortype ', ' instancetype ', ' inttype ', ' lambdatype ', ' ListType ', ' longtype ', ' memberdescriptortype ', ' methodtype ', ' moduletype ', ' nonetype ', ' notimplementedtype ', ' ObjectType ', ' slicetype ', ' stringtype ', ' stringtypes ', ' tracebacktype ', ' tupletype ', ' typetype ', ' Unboundmethodtype ', ' Unicodetype ', ' xrangetype ', ' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ '

How do you know that these properties are actually Python's built-in types?

For example:

>>> types. Dictionarytype<type ' dict ' >>>> types. Dicttype<type ' dict ' >>>> type ({}) <type ' Dict ' >

Visible, types. Dicttype and types. Dictionarytype is actually the built-in type Dict, which is the type ({}).

Methods for Python type find path (method Resolution Order)

Python supports multiple inheritance, when referencing a property that inherits instances of more than one type, how to determine the order in which properties, methods are found, called method lookup paths.

A class in python that inherits from more than one type uses a method called C3 to find the path (the Python 2.3 method Resolution Order), and the __mro__ property of a custom type can view the method lookup path for that type:

>>> class D (object): ...     D = 100...>>> class B (d): ...     Pass...>>> class C (D): ...     Pass...>>> class A (B, C): pass...>>> a.__mro__ (<class ' __main__. A ';, <class ' __main__. B ';, <class ' __main__. C ';, <class ' __main__. D ';, <type ' object ' >)

You can only view the __mro__ property of one type, which is read-only and the order in which each type is displayed is the order in which the properties, methods of that type are accessed.

  

The relationship and difference between type and object in Python

http://blog.csdn.net/cpp_chen/article/details/9168909

All sequences (Sequence) are iterative (iterable), but iterative objects are more than Sequence:

    • The sequence must be orderly, but iterative objects are not necessarily, such as set objects, which can be traversed, but unordered, and therefore cannot be indexed, sliced, etc.

python--built-in types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.