python--Built-in objects

Source: Internet
Author: User

Python's built-in objects
Object type Constants Example/usage
Number (numeric) 3.14159, 1234, 999L 3+4j
String (String) ' Spam ', ' Guido '
List (lists) [1,[2, ' three '],4]
Dictionary (dictionary) {' food ': ' spam ', ' taste ': ' Yum '}
Tuple (tuple) (1, ' spam ', 4, ' U ')
File (Files) Text=open (' Egges ', ' R '). Read ()
Numeric constants
Constant Explain
1234,-24, 0 Normal integer (Long integer of C)
999999999999999L Long integers (infinite size)
1.23, 3.14e-10, 4E210, 4.0e+210 Floating-point number (double integer of C)
0177, 0x9ff Octal and hexadecimal constants
3+4j, 3.0+4.0J, 3J Complex constants
Expression manipulation and preprocessing of numbers
Operation Describe
X or Y Logical OR (only X is False, Y is computed)
Lambda args:expression anonymous functions
X and Y Logic and (only if x is true, y is calculated)
Not X Logical Inverse
<,<=,>,>=,==,<>,!=, Compare operations
Is, are not, Identity testing
In, not in Sequence member Relationship Testing
x | Y Bit or
x ^ y Bit XOR or
X & Y Bit and
X<<y, X>>y Move x left or right to Y-bit
X+y, X-y Add/merge, subtract
X*y, x/y, x%y Multiply/Repeat, except, remainder/format
-X, +x, ~x One-yuan reverse, consistent, bit-complement
X[i], X[i:j], x.y, X (...) Index, shard, qualification, function call
(...), [...], {...}, ‘...‘ Tuple, list, dictionary, convert to string

Built-in functions and built-in modules for digital processing: (modules are external components, but built-in functions are included in namespaces)
>>> Import Math
>>> Math.PI
3.14159265359
>>> ABS ( -42), 2**4, pow (2,4)
(42,16,16)

String string constants and operations
Operation Explain
S1 = ' ' Empty string
S2 = "spam S" Double quotes
block = "" "..." " " Three-quote block
S1 + s2 Merge
S2 * 3 Repeat
S2[i] Index
S2[I:J] Sharding
Len (S2) Length
"A%s parror"% ' dead ' string format
For x in S2, Iteration
' m ' in S2 Member relationships

String modules can be used everywhere in the most standard C library of strings processing tools
Regex and RE modules field a regular expression match for a string

An empty string can be written as an empty two quotation mark in the middle. Note string constants can be enclosed in single or double quotes, and both work equally, but they all allow a quotation mark character to appear inside the string without escaping with a backslash.

Three-quote block (table line 3rd): When strings are surrounded by three quotes, they can span multiple lines. Python collects all three-quote text into a multiline string with an embedded line break.

>>> Import String #标准的模块
>>> S = "Spammify"
>>> String.upper (S) #转化为大写
>>> String.find (S, "mm") #返回索引的子串
>>> ("String.atoi"), ' #转化字符串 '. Atoi converts a string into a number, and converts any object that is quoted by an anti-quote into a string form.
(42, ' 42 ')
>>> String.Join (S, "mm", "XX") #split把一个字符串截成一列被界定符和空格符围绕的子字符串. Join puts them together, and two has a transitive delimiter or space in the middle. Substituting "XX" for "MM" is a roundabout method, but this is an arbitrary alternative to global substrings.
' Spaxxify '

Common Types of concepts

The general concept is applied in many applications. For a built-in type, all types of operations of the same category are the same.

Shared operations of the same type: strings are immutable sequences that cannot be changed in the original, but are ordered collections that can be accessed based on offsets.

There are three types of operations in Python:
Numbers: Support for + and * operations
Sequence: Supports operations such as indexing, sharding, merging, etc.
Mapping: Support for operations such as key indexing

Variable types can be changed in situ, immutable types cannot be changed in situ, only one copy can be made.

List

Main attributes: An ordered set of arbitrary objects, variable length, heterogeneous, arbitrary nesting, a variable type of sequence, an array of objects applied by offset access

Common list constants and actions

Operation Explain
L1 = [] An empty list
L2 = [0,1,2,3] Four items: index 0 to 3
L3 = [' abc ', [' def ', ' Ghi '] Nested sub-lists
L2[i], L3[i][j] Index
L2[I:J] Sharding
Len (L2) Request length
L1 + L2 Merge
L3 * 3 Repeat
For x in L2, Iteration
3 in L2 Member relationships
L2.append (4), Method: Growth
L2.sort (), Sort
L2.index (1), Find
L2.reverse () Reversal, etc.
Del L2[k]
L2[I:J] = []
Narrow
L2[i] = 1, Index Assignment
L2[I:J] = [4,5,6] Shard Assignment
Range (4), xrange (0,4) Generate a list/tuple of integers

Append and sort change the associated list object in place, but do not return the list (strictly speaking, they all return a value called none), and if it is written as L = L.append (X), you will not get an L-adjusted value (in fact, lose a reference to the list at the same time). When using properties such as append, sort, the object itself is changed at the same time, so no re-assignment is necessary.
L.append (X) and l+[x] effects are similar, but the former is changed in place, and the latter generates a new list. Unlike the "+" merge, append does not need to generate new objects, so it is faster.

Dictionary

In addition to the list, the dictionary is probably the most resilient built-in data structure type in Python. A list is an ordered collection of objects, a dictionary is a set of unordered, and the main difference is that the entries in the dictionary are accessed by keys, and the list is accessed by offsets. The main properties of a dictionary are: access by key instead of offset, arbitrary set of objects, variable length, heterogeneous, arbitrary nesting, variable mapping type, object reference table (hash list, but at the bottom, dictionaries store reference as list)

Common Dictionary object constants and operations

Operation Explain
D1 = {} An empty Dictionary
D2 = {' spam ': 2, ' Eggs ': 3} Dictionary of two items
D3 = {' food ': {' Ham ': 1, ' Egg ': 2}} Nesting
d2[' eggs '],d3[' food ' [' Ham '] Indexed by Key
D2.has_key (' eggs '), Method: Member Relationship test,
D2.keys (), List of keys
D2.values () List of values, and so on
Len (D1) Length (number of items stored)
D2[key] = new,
Del D2[key]
Add/change
Delete


As with lists, assigning values to an existing index in a dictionary alters the value associated with it. Unlike lists, once you assign a value to a new dictionary key, you create a new entry in the dictionary. Not in the list, because Python thinks that the offset beyond the end of the list is out of bounds. To expand a list, you use the Append method or the Shard to assign a value.

>>> table = {' Python ': ' Guido van Rossum ', ' Perl ': ' Larry Wall ', ' Tcl ': ' John ousterhout '}
>>> for Lang in Table.keys (): Print lang, ' \ t ', Table[lang]

Because dictionaries are not sequential, you cannot iterate through a for statement just as you would in a string and a list. Traversing the items requires the method described above.

Please Note: Dictionary interface

Some Python extensions also provide the same interface as the dictionary for both the surface and the actual work.

Python's dbm Key Access file interface looks particularly like an already open dictionary: The available key index to store and get the string:
Import anydbm
File = Anydbm.open ("filename") #连接到扩展文件
file[' key '] = ' data ' #通过键存储数据
data = file[' key ' #通过键取得数据
If we replace "anydbm" with "shelve", we can store the entire Python object (shelve is a persistent Python database accessed by key)

In the work of the Internet, Python's CGI scripts also support the implementation of a dictionary-like interface. A pair of CGI. The invocation of the Fieldstorage range produces a dictionary-like object. There is one entry for each input field on the Client Web page:
Import CGI
form = CGI. Fieldstorage () #解析格式数据 (Stdin,environ)
If Form.has_key (' name '):
Showreply (' Hello, ' + form[' name '].value)

Considerations for using dictionaries: sequence operations cannot work, assignments to new indexes add items, keys are not necessarily always strings

Tuple tuples

Tuples consist of simple groups of objects. Tuples are similar to lists except that they cannot be changed in place (they are immutable) and are usually written in a string of parentheses. The attributes of a tuple are: an ordered set of arbitrary objects, an array of invariant length, exceptions, arbitrary nesting, and object references, by means of an offset access, an immutable sequence type.

Common tuple constants and operations

Operation Explain
() An empty tuple
T1 = (0,) A tuple of only one item (not an expression) single-tuple
T2 = (0,1,2,3,4) A tuple with five items
T2 = 0,1,2,3,4 Another tuple with five items (same as the same line)
T3 = (' abc ', (' def ', ' Ghi ')) Nesting
T1[i], T3[i][j]
T1[I:J]
Len (t1)
Index
Sharding
Request length
T1+t2
T2*3
Merge
Repeat
For x in T2,
3 in T2
Iteration
Member relationships

The +, *, and Shard operations return new tuples, and tuples do not provide our methods in lists and dictionaries. Generally speaking, in Python, only mutable objects can output callable methods.

If you have a list, why use tuples?

The immutability of tuples can provide some overall performance; What you can decide is that a tuple in one program will not be changed by another reference. And the list has no such guarantee.
Some built-in operations also require tuples rather than lists. For example, when a built-in function makes a dynamic call to a function, the parameter table is made up of tuples
There is a principle from practice: Lists can be used for tools that want to change the ordered set; tuples deal with other things

File

Built-in function open creates a Python file object that can be used as a link to a file on your computer. After calling open, you can read and write related external files by invoking the method of the file object. Strictly speaking, a file is a pre-established C extension type that provides a layer of wrapping on top of the underlying C Stdio file system. In fact, the file object method corresponds to the one by one function in the C standard library.

Common file Operations

Operation Explain
Output = open ('/tmp/spam ', ' W ') Generate Output file (' W ' for Write) (' A ' stands for file opening for appending content at the end of the file)
input = open (' Data ', ' R ') Generate Input file (' R ' for read)
S = Input.read () Read the entire file into a string
S = Input.read (N) Read N bytes (one or more)
S = Input.readline () Read Next line (over line end tag)
L = Input.readlines () Reads the entire file into a list of line strings
Output.write (S) Writes a string s to a file
Output.writelines (L) Writes all the row strings in the list L to a file
Output.close () Manual shutdown (or during garbage collection)

The Seek function resets the current position in a file. Flush force flush cache termination output for ease of writing, etc.

>>> myfile = open (' MyFile ', ' W ')
>>> myfile.write (' Hello text file\n ')
>>> Myfile.close ()
>>> myfile = open (' myfile ', ' R ')
>>> Myfile.readline ()
' Hello text file\012 '
>>> myfile.readline () #空字符串: End of File
‘ ‘

Available Tools for file classes

File based on profile
OS module provides the use of low-level profile-based interfaces

DBM Key (keyed) file
ANYDBM provides an interface for accessing files by key

Persistent files
Shelve and pickle modules provide support for saving the entire object (not just a simple string)

Pipeline
The OS module also provides a POSIX interface for easy processing of pipelines

Other
There are optional interfaces to the database system, B-tree-based files, etc.

====== Summary ======

operator Overloading : If you want to provide a new special sequence object that consists of a built-in sequence, write a class that can reload indexes, shards, merges, and so on:
Class MySequence:
def __getitem__ (Self,index):
# [index], for x in self, x in self
def __getslice__ (Self,low,high):
# called on Self[low:high]
def __add__ (Self,other):
# called on Self + other
The built-in type of Python is the true pre-coded C extender type. When you write your own code, you need to know the category of the type.

commonality : Lists, dictionaries, and tuples can include objects of any kind; lists, dictionaries, and tuples can be nested arbitrarily; lists, dictionaries can be expanded and scaled up dynamically

comparison, equality, and truth:
    = = operators test for equality of values
        Python runs an equality test, recursively comparing all the inline objects.
    is operator conformance to test objects
        Python tests if they are really the same object (for example, in the same address)
Example Object Truth

Object Value
"Spam" Really
" " False
[ ] False
{ } False
1 Really
0.0 False
None False

None is always considered false, and he is the only special data structure in Python. It usually plays an empty placeholder, particularly like a null pointer in the C language.

type level of Python: Anything in Python is an object type that can be handled by a Python program.

numbers → integers → integers, long integers
→ Floating-point number, plural

Collection → sequence → immutable → strings, tuples
→ variable → list
→ maps → dictionaries

Callable → functions, classes, methods → bindings
→ Non-binding

Other → modules, instances, files, empty

Internal → type, code, frame, trajectory

FAQ for built-in types

    1. assignment generates a reference instead of a copy
      >>> L = [x-ray]
      >>> m = [' × ', L, ' Y '] #对L的嵌套引用
      >>> M
      [' x ', [n/A] , ' y ']
      >>> l[1] = 0
      >>> M
      [' X ', [1,0,3], ' Y ']
      Workaround: This effect is usually important only in large programs, and sometimes shared references are never what you really want. If not, you can avoid sharing objects by copying them. In the list, you can always generate high-level copies that are generated using an empty finite shard.
      >>> L = [l[]
      >>> m = [' X ',:], ' Y '] #一个嵌入的L的拷贝
      >>> l[1] = 0 #只改变L, do not change M
      >&G t;> M
      [' X ', [[+], ' Y ']
    2. repeated addition of the same layer depth. When we introduce the repetition of the sequence, we say that he is somewhat like adding some multiples of itself after the sequence. This is true, but when mutable objects are nested, the effect may not always be what we think.
      >>> L = [4,5,6]
      >>> X = L * 4    # similar to [4,5,6]+[4,5,6]+ ...
      >>> Y = [L] * 4 # [l]+[l]+ ...
      >>> X
      [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
      >>> Y
      [[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6 ]]
      >>> l[1] = 0 # affects Y but does not affect x
      >>> x
      [4, 5, 6, 4, 5, 6, 4, 5, 6, 4, 5, 6]
      >>> Y
      [[4] , 0, 6], [4, 0, 6], [4, 0, 6], [4, 0, 6]]
      Workaround: This is indeed another way to trigger a share to be referenced by an object, so that the same method above can be applied to the left. And if you remember that repeating, merging, and Shard copying are just the top level of manipulating objects, this kind of example is more useful.
    3. Immutable types cannot be changed in situ
      >>> T = (all in all)
      >>> t[2]=4
      Traceback (most recent):
      File "<stdin>", line 1, in?
      Typeerror:object does not support item assignment
      >>> T = t[:2]+ (4,)
      >>> T
      (1, 2, 4)
      Workaround: Create a new object with sharding, merge, and so on. However, if necessary, assign the value back to the original reference. This looks like an extra coding effort, but the advantage of this is that the previous problem does not occur when using immutable objects such as tuples and strings. Because they can be changed in their original location, they do not produce side effects similar to those in the list.

python--Built-in objects

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.