Python Learning Notes (iv) Python object

Source: Internet
Author: User
Tags repetition shallow copy

1,pythons Object Features

From a more specific point of view, Python programs can be decomposed into modules, statements, expressions, and objects. A program consists of modules that contain statements, statements that contain expressions, and expressions that create and manipulate objects. Python provides a powerful object type as part of the language, and unless there are special objects that the built-in type cannot handle, it is best for users to always use built-in objects. Python's built-in object types are powerful and efficient, and are a core part of a Python program that makes programming simple. The advantages of using built-in objects are:

(1) Make programming easier-built-in objects can often represent all the results of a problem domain, and they can use powerful tools such as collections, search tables, and so on, using only built-in object classes to do a lot of work.

(2) Built-in objects are extended components-for complex tasks, users need to provide their own objects, using Python classes or C-language interfaces. But objects that are implemented manually are often built on the basis of a type such as dictionaries and lists.

(3) Built-in objects more efficient-python's built-in type optimizes the algorithm for implementing data structures using C, so the performance is better than the structure of its own structures.

(4) Built-in objects are part of the Python language standard-python built-in tools are standard, consistent, and the original framework relies on the implementation environment.

Is the core built-in object type provided by Python, and everything the Python program handles is an object. Python's type is dynamic and strongly typed, the Python object has no type declaration, and the expression that runs is the object type that Python establishes and uses, and once the object is created, it is bound to the type of action that the response is-such as string manipulation only for characters.

In the underlying language, you must carefully release the object space that is occupied when the object is not needed. Python is simpler, and after the last reference to an object, the memory occupied by the object is automatically cleaned out (for example, by rev=0, the memory space occupied by the Object Rev is automatically freed). Such a garbage collection mechanism makes it possible for users to be free to use objects without worrying about creating or cleaning up object space.


All Python objects support comparison operations-test equality, comparison size, and so on-whose comparisons always traverse all parts of the object, knowing that results can be obtained. The difference that is first found in the process determines the comparison result.

The same object types can be "greater than, less than equal" comparison operations, the more special is "= =" and "is" to support comparisons between different types of objects. the operator "= =" tests whether the contents of the object (including elements) are the same (not necessarily the same object), and the operator "is" tests whether the two are the same object (in the same address space), such as determining whether two references point to the same object.

Classification of 2,python objects in general sense

Python is all about a type of object, even if it is a type of object, and "Any object's type" is an object of type "types". Summarizes all the built-in object types that Python allows and the relationships between them. Call the built-in function type (x) to return the types of the object "X".


In addition to Python's core objects, a typical Python installation also includes other available object types, allowing extensions to the C language or Python classes such as: Regular Expression objects, dbm files, network sockets Soket, and so on. The difference between them and python built-in types is that they must be imported before they can be used.

In general, Python's core data types are divided into three categories, each with some specific operations. They are: numbers, sequences, and mappings (support for key-based indexes, such as dictionaries), this section focuses on the Python sequence.

In Python, the most basic data structure is the sequence (sequence). Each element in the sequence is assigned an ordinal-that is, the position of the element, also known as an index. The first index is 0, the second one is 1, and so on. The last element in the sequence is marked as-1, the second-penultimate element is-2, and so on. All sequence types can perform certain operations. These actions include: index (Indexing), Shard (sliceing), add (adding), multiply (multiplying), and check whether an element belongs to a member of a sequence (membership). In addition, Python has built-in functions for calculating the length of a sequence, finding the largest and smallest elements. Python contains a sequence of 6 built-in, including lists, tuples, strings, Unicode strings, buffer objects, and Xrange objects.

The Python object is divided into mutable objects and immutable objects from the same place. mutable objects support original modifications, including lists and dictionaries, and immutable objects do not support the need to change, including numbers, strings, and tuples.

3,python core built-in object types

i) Digital-python digital objects include general types: integers, floating-point numbers, and infinite-precision long integers (automatically converts integers to long-integer s), complex numbers, sets, etc., and supports general operations such as addition, subtraction, multiplication, and power. Floating-point numbers are printed in full precision (multiple digits after the decimal point) and user-friendly (when printed with print, with less decimal places). Python provides numeric action types that include the math class, the random class, and so on.

In addition, Python supports decimal objects, which are created through an imported module call function. Although there is a slight loss of precision relative to the floating-point number, the decimal type is the ideal tool for the performance of fixed precision and for the determination of digital accuracy. The result of the 0.1+0.1+0.1-0.3 should have been 0, but the result was 5.551115123125783e-17. With the help of decimal objects:

From decimal import decimaldecimal (' 0.1 ') +decimal (' 0.1 ') + decimal (' 0.1 ')-decimal (' 0.3 ') =decimal (' 0.0 ')

The decimal module also allows you to set the precision of the decimal place.

II) string-record text information, strictly speaking a sequence of characters. The Python string is immutable-that is, it can no longer change its value after it is created. For example, after a string change, the user cannot change the value of any position in the string, but can be re-assigned by creating a new object with the same variable name, such as S= ' a ' +s[1:4] will create a new string S string operation containing the length, index, Shard (String[i:j], String from I to J bits), merge (string +), repeat (String *, such as string*8 for string repetition 8 times), find, replace (create a new string object, the original string value is unchanged), etc. The user can view the action method of the string through Dir (s) (S is a string object), where the attribute without an underscore is.

There is no single character of this type in Python, but you can use a string with only one character. A python string can be either a pair of single quotes or a pair of double quotation marks, which can be embedded in a single quotation mark character in a double-quote string, or in the case of a double-quote string in which the double quotation mark must be an escape character \, and a single quote string. If you want to keep ' \ ', there are two ways: A, if the letter r (uppercase or lowercase) appears in front of the first quotation mark of the string, it will close the escape mechanism, B, using a double backslash "\ \"

Sanchong quotation marks (both single and double quotes) can be used to write multiple lines of text data, which simply begins with a triple quotation mark and ends with a Sanchong quote, and Python inserts a newline character "\ n" in line break. The Sanchong quotation mark mechanism can be used to temporarily abolish a Python program, embedding "" "before and after the program.

The "%" operator in the string provides a concise way to write a multi-string substitution. such as ' Your name is%s, Your class is%d '% (' Aidan ', 1 '),%d for inserting a numeric decimal integer, and%s for inserting a string (any object can be converted to a string insert). The specific structure and code meaning of the "%" operator are as follows.


III) List-list is the most common sequence provided by Python, and the list is an ordered set of objects of any type, with no fixed size and can be arbitrarily extended.

The list is the most flexible, ordered collection object type in Python and can contain objects of any type: numbers, strings, other lists. The list is a mutable sequence object, can be modified in place, and can be read by offset. Technically, the list contains 0 or more references to other objects, inside the standard Python interpreter, and the list is the C array.

The list supports all sequence operations, and there are list-specific types of operations such as append, delete, pop, insert, and so on, where the user can view the list's action method through Dir (l) (L is a list object), where the attribute without underlining is. Although the list does not have a fixed size, it is still not allowed to reference elements that do not exist (in the list, if necessary, the None object can be used for placeholders), and to increase the list you can call the Append method. The list supports any combination of nesting, such as constructing a two-dimensional array list resolution, which makes it easy to get a column in The matrix (the matrix is stored by row).

m=[[1,2,3],      [4,5,6],       [7, 8, 9]] col2 = [raw[1] for Raw in M] available col2=[2,5,8]diag=[m[i][i] for i in [0,1,2]] Get diagonal element dia G=[1,5,9]

V) Dictionary-python Dictionary is a map, accessed by keys, and simply maps keys to values. Dictionaries are also variable, dynamically scalable, dictionaries are written in curly braces, contain columns of "key: value" pairs, "key" s can be numbers and strings, or even tuples. A dictionary is an unordered collection of arbitrary objects, supports nesting, belongs to a modifiable mapping type (where it can be modified), is inherently based on a hash table, and stores a reference to an object.

Referencing a nonexistent key in a dictionary causes an error, and in order to prevent referencing a nonexistent key, a trick is to first Test by in (3.0 after canceling the Has_key () method) and in conjunction with the IF Statement branch. The following example takes Python3.1 as an example

D={' A ': 1, ' B ': 2, ' C ': 3}if ' d ' in D:     print (d[' d ']) Else:     d[' d '] = 4

VI) tuples-tuples provide integrity constraints, which are an ordered set of arbitrary objects that can be offset by an invariant sequence type (immutable), fixed length, and support nesting. Tuples are best thought of as an array of object references, enclosed in parentheses, separated by commas, and tuples support all operations of a sequence. The non-modifiable nature of Ganso provides an integrity protection relative to the list, ensuring that it is not modified by another reference while the program is running. Tuples can also be keys for dictionaries.

VII) file-The file object is the Python program's main interface to the external file on the computer, and invoking the built-in function open creates a file object. File operations include write, read, close, and so on. The text file in the Python program takes the form of a string, and the original data from the text is a string that the user can convert to other types of objects as needed (using a conversion tool such as eval to convert the string to an object), and the user must also pass the first formatted string when writing to the file. In addition, the Pickle module is a universal data formatting and parsing tool that allows users to store various types of Python objects directly in the file, without having to move strings around. A struct module can construct or parse a packaged binary data file

Calling the file Close method will end the call to multiple external files, and calling close manually is a good programming practice.

VIII) Other Python built-in object types also include a collection (which differs from the sequence in that the collection does not contain a positional order), a Boolean value (whose value is Tru or false), and also supports user-defined classes.

4,python built-in types considerations

1) The assignment generates a reference

Any assignment in Python is essentially a one-time reference to an object, which must be noted in shared references to mutable objects, such as nesting. In order to avoid the problem of modification caused by sharing the application, the user can make explicit copy (need deepcop,deepcopy will copy each element completely, produce new object; [:] is shallow copy, for list, nested in dictionary, shallow copy or only copy reference) To generate a new, non-shared object.

l=[1,2,3]m=[' x ', L, ' y '] #运行结果为: m=[' x ', [All-in-one], ' Y '],l is a reference l[1]=0m #M也将随着改变, changed to m=[' X ', [1,0,3], ' y ']

2) immutable types cannot be modified in situ

The immutable types in Python cannot be modified in-place, and if needed, users can create a new object with shards, merges, and so on, and assign the value to the original variable (a new reference).

3) Notice the Loop object

If an object contains a reference to itself called a looping object, Python detects that the loop object will print as [...]. Looping an object may cause the program to fall into an unexpected loop, which should be used with caution.

4) Sequence Repetition

The repeats, merges, and shards of a sequence exist only at the top level of the sequence (that is, not deep into the nested structure), so if L is a list, l*4 (the top element is each element of L) and [L]*4 is (the top-level element is a list [], the element is nested with a reference to the list L).


Python Learning Notes (iv) Python object

Related Article

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.