Python objects, names, and bindings

Source: Internet
Author: User

Python advanced-objects, names, and bindings

Write in front

If not specifically stated, the following are based onPython3

1. All objects

PythonPhilosophy:

All objects in Python

1.1 Data models-objects, values, and types

An object is an Python abstraction of the data. Pythonall data in a program is represented by the relationship between objects or objects. (In a sense, in order to conform to the von Neumann "stored computer" model, Python the code is also an object.) )

PythonEach object in the is an identity, a value, and a type. Once an object is created, its identity will never change, and the identity can be used as an address in memory for the object. isoperator to compare the identity of two objects; the id() function returns an Integer that represents the identity of the object.

CPython Implementation Details: in the CPython interpreter implementation, the id(x) function returns the stored x memory address

The type of object determines what operations the object supports (for example, does an object have a length?). ), and also determines the possible values for that type of object. type()The function returns the type of the object (the type itself is also an object). As with identity, the type of the object is immutable [1].

The values of some objects can be changed. The object that can change the value is also called variable (mutable); once created, the constant value of the object is also called immutable (immutable). (When the Immutable container object contains a reference to a Mutable object, the value of the immutable container object is changed when the Mutable object value changes; However, the immutable container object is still considered immutable because the collection of values that the object contains is indeed immutable.) Therefore, immutability is not strictly equivalent to having an immutable value, which is subtle. First, the value of the immutable container object is a collection that contains references to other objects, which can be treated as addresses, even if the contents of the address are changed, and the addresses themselves in the collection are unchanged. Therefore, immutable container objects or immutable objects. The variability of an object depends on its type, for example, numbers, strings, and tuples are immutable, but dictionaries and lists are mutable.

Objects are never explicitly destroyed, and are garbage collected when the object is unreachable (the object is not referenced). An interpreter implementation allows garbage collection to be delayed or ignored directly-depending on how garbage collection is implemented, as long as no objects are recoverable.

CPython Implementation Details: CPython The interpreter implementation uses the reference-count mode to detect cyclic link garbage in a way that reclaims most unreachable objects, but does not guarantee that recycled garbage is recycled. View gc the documentation for the module for more information about controlling the recycling garbage collection. Other interpreters are implemented CPython differently and CPython implementations may change in the future. Therefore, you cannot rely on the garbage collector to back up unreachable objects (so you should always explicitly close file objects.) )。

It is important to note that using the tool's debug tracing feature may cause objects that should be reclaimed to survive, and using try ... except statements to catch exceptions can also keep the object alive.

Some objects refer to external resources, such as files or Windows. It goes without saying that resources are freed when the object holding the resource is garbage collected, but because there is no mechanism to guarantee that garbage collection will happen, these resource holders also provide a way to explicitly release external resources, often using close() methods. Explicitly releasing resources in a program is highly recommended. try...finally Statements and with statements facilitate the release of resources.

Some objects contain references to other objects, which are called containers . Tuples, lists, and dictionaries are containers. A part of the referenced container value. In most cases, when talking about the value of a container, we imply that the container contains a collection of object values rather than an object's identity collection; however, when we talk about the variability of the container, we imply the identity of the object contained in the container. Therefore, if a non-mutable object (such as a tuple) contains a reference to a Mutable object, its value changes when the Mutable object changes.

Type affects most of the behavior of an object. In some cases even the importance of the identity of an object is affected: For an immutable type, the operation that computes the new value may actually return a reference to an object that already exists, with the same value and type, but this is not possible for mutable objects. For example, a = 1; b = 1 after a statement is executed, a and b may or may not refer to the same object that has the same merit, this depends on the interpreter implementation. However, after the statement is c = []; d = [] executed, it can be guaranteed c and d will point to a different, unique, newly created empty list. (Note that c = d = [] assigning the same object to c and d )

Note: The above translation is from the types version of the Python Language references#data model# Objects, values, 3.6.1.

1.2 Summary of objects

The official documentation has already Python described the object in detail, and here is a summary.

Three properties of the object:

    • Identity identification
      Uniquely identifies an object, is immutable, CPython and the interpreter implements the memory address of the object.
      Action: id() The built-in function id() function returns an integer that identifies the object and is compares the identities of two objects.
      Example:

      >>> ID (1) 1470514832>>> 1 is 1True
    • Type
      Determines the operations supported by the object, the possible values, or immutable.
      Action: type() The built-in function returns the type of the object
      Example:

      >>> type (' a ') <class ' str ' >
    • Value
      data, variable/non-volatile
      Action: == the operator is used to compare the values of two objects, and the other comparison operators compare the size of objects to each other.
      Example:

      >>> ' python ' python ' >>> 1 = = 2False

mutable and immutable : it is generally assumed that an immutable object is an immutable object, and that a variable value object is a Mutable object, but be aware that immutable collection objects contain Mutable object reference members.

PythonThe objects in:


#-*-Coding:utf-8-*-# filename:hello.py ' a test module ' author = ' Richard Cheng ' import sysclass Person (object):    ' ' Person class "    def init (self, Name, age):        self.name = name        self.age = Agedef tset ():    print (Sys.path) C5/>p = person (' Richard ', ')    print (P.name, ': ', P.age) def main ():    tset () if name = = ' main ':    Main ()


PythonThere are many objects in this code, including the hello module object, the Person class object created, several functions such as test main function object, number, string, and even the code itself is an object.

2, the name is "variable"

Almost all languages have "variables", strictly speaking, Python the variables should not be called variables, called names more appropriate.

The following translations from Code like a pythonista:idiomatic python # python have "names"

2.1 Other languages have variables

In other languages, assigning a value to a variable is like putting a value in a "box."
int a = 1;

aThe box now has an integer 1 .

Replace the contents of the box with the value assigned to the same variable:
a =2;

The box now a has an integer in it.2

Assign a variable to another variable, copy the value of the variable, and put it in a new box:
int b = a;

bIs the second box with a copy of the integer 2. athe box has a separate copy.

2.2 Python has a name

Python, a name or identifier is like tying a label to an object.
a = 1

Here, the integer object 1 has a a label called.

If you reassign a a value, simply move the label to another object:
a = 2


Now the name is a affixed to the integer object 2 . The original integer object 1 no longer has a label a , it may still exist, but it cannot be accessed by the tag (when the a object has no references, it is recycled.) )

If you assign a name to another word, simply bundle another name tag onto the existing object:
b = a

The name b is just a a second label bound to the same object as the reference.

Although Python "variable" is commonly used in (because "variable" is a universal term), the real meaning is the name or identifier. Pythonthe variable in is worth the tag, not the box worth the load.

2.3 Pointers? Reference? Name?

C/C++There is a pointer in, a Java reference in, Python the name in some degree equivalent to pointers and references.

Examples of other languages in section 2.1 are only for their basic types, and if the pointer or reference is the Python same as the name. This also explains to some extent that Python the object-oriented implementation is more thorough.

2.4 Name-supported operations

What can I do with a variable? Declare variables, use variables, and modify the values of variables. As an Python important concept in the name, the operations that can be done with it are:

    • The name needs to be defined before it can be used, as the variable needs to be declared first.

    • binding : A single existence of a name is meaningless, and it must be bound to an object.

    • Re- binding : The name can re-reference another object, which is the re-binding.

    • Reference : Why define a name, to use it.

3, the Art of binding

Names and objects, what will inevitably happen between them.

3.1 Declaration of variables

In other C/C++ Java high-level languages, variables need to be declared, or defined, before they can be used. The variables are declared in the following Java :


public static void Main (string[] args) {        int i = 0;//declare First, use        System.out.println (i);//use variable i}


In this way, you can use it wherever you have access to i the scope of the variable i . Are there other ways to declare variables? It doesn't seem to be there.

3.2 Definition of the name of the word

PythonThere are many ways to define a name, such as a function definition, which is the name of a reference function object, a class definition, a class name that refers to the name of a class object, a module definition, and a module name that refers to the name of a module object; Of course, the most intuitive is the assignment statement.

Assignment statements

The official description of the assignment statement (address):

Assignment statements is used to (re) bind names to values and to modify attributes or items of mutable objects.

That

An assignment statement is used to bind or rebind a name to a value, and also to modify the properties or items of a mutable object.

So, what we care about is that the assignment statement binds the name and value (the object) together.

To see a simple assignment statement:


A = 9


PythonWhen working with this statement:

    1. You first create an object in memory that represents an integer 9 :

    1. Then create the name and a point it to the above object:

The above procedure is bound by the moniker of the assignment statement. Once the name is first bound to the object, the name is defined in the current namespace and can then be referenced in the scope that can be accessed to the namespace.

3.3 Referencing immutable objects

Once the name is defined, the name is used, and the name is used as the "reference name". When a name points to a mutable object and an immutable object, the use of a name can have a different performance.


A = 9       #1a = a + 1   #2


When statement 1 finishes executing, the name a points 9 to the object that represents the integer:

Because an integer is an immutable object, the name is referenced at Statement 2, a attempting to represent 9 an integer + 1 object, but the value of the object cannot be changed. Therefore, add the integer value represented by the 9 object 1 and 10 create a new integer object as an integer:

Next, take the name a 重绑定 to the new object and remove the name from the original object's reference:

Using a id() function, you can see that a the address of the object to which the name is pointing does change:


>>> a = 9>>> ID (a) 1470514960>>> a = a + 1>>> ID (a) 1470514976


3.4 Referencing mutable objects

3.4.1 Example 1: Changing the value of a mutable object

A mutable object can change its value without causing an address change:


>>> List1 = [1]>>> ID (list1) 42695136>>> list1.append (2) >>> ID (list1) 42695136> >> list1[1, 2]>>>


Executes the statement list1 = [1] , creates an list object, and adds it to its value set 1 , list1 pointing the name to the object:

The execution statement list1.append(2) , because list it is a mutable object, can be added directly to its value set 2 :

The change list1 in the address of the object that is worth changing does not cause the reference.

3.4.2 Example 2: Variable Object circular Reference

Let's look at a more "strange" example:


values = [1, 2, 3]values[1] = Valuesprint (values)


Looking at one glance, the expected result should be


[1, [1, 2, 3], 3]


But the actual result is:


[1, [...], 3]


We know that the list elements in the can be of various types, and the list types are possible:

3.4.3 Example 3: Re-binding mutable objects

Observe the following code snippet:


>>> List1 = [1]>>> ID (list1) 42695136>>> list1 = [1, 2]>>> ID (list1) 42717432


Two times the name of the output list1 refers to the object's address differently, because the second statement list 1 = [1, 2] re-binds the name:

3.5 Shared objects

When two or more than two names refer to the same object, we call those names a shared object. Shared objects can vary in variability and performance.

3.5.1 Sharing immutable objects

function attempt_change_immutable to i change the value of the parameter to2


def attempt_change_immutable (i):    i = 2i = 1print (i) attempt_change_immutable (i) print (i)


Output:


11


If you are not surprised by the output, it is not novice ^_^.

    1. First, the parameters of the function are i i not in the same namespace as the global names, so they do not affect each other.

    2. When a function is called, all two names i point to the same integer object.

    3. The value modified in the function i is 2 because the integer object is immutable, so the new value is 2 an integer object, and the name in the function is i bound to the object.

    4. iThe binding relationship of the global name has not been changed.

It is worth noting that this part of the content is related to namespaces and scopes, and an article introduces them for reference.

3.5.2 Sharing mutable objects

attempt_change_mutablethe function adds a string to the list.


def attempt_change_mutable (list_param):    list_param.append (' test ') List1 = [1]print (list1) Attempt_change_ mutable (list1) print (List1)


Output


[1] [1, ' Test ']


You can see that the function successfully changed the list1 value of the list. When passing a parameter, the name refers to the list_param object with the same name, which list1 is mutable and the value of the object has been successfully modified in the function.

First, the name list_param and name point to the list1 object:

Then, the list_param value of the object is modified by name:

Finally, this modification is visible to the name list1 .

3.6 When the binding occurs

In general, there are some of the following behaviors that trigger moniker bindings:

    • Assignment operation;a = 1

    • function definition;

      def test ():    Pass

      Bind a name test to a function object

    • Class definition:

      Class Test (object):    Pass

      Bind a name Test to a class object

    • function to pass parameters;

      def test (i):    passtest (1)

      ibind a name to an integer object1

    • importStatement:

      Import Sys

      Binds the name sys to the specified module object.

    • forCycle

      For I in range (Ten):    Pass

      The name is bound/re-bound for Each loopi

    • asOperator

      With open (' dir ', ' R ') as F:    passtry:    passexcept nameerror as NE:    Pass

      with openstatement, the binding of a name that occurs in an exception capture statement as

4. Other instructions

Cond...

Reference

    1. The Python Language references#data model# Objects, values, types

    2. Python's name Binding

    3. Python all objects

    4. Code like a pythonista:idiomatic Python

    5. Python Basics (5): In-depth understanding of assignments, references, copies, scopes in Python

Footnote

[1] under certain control conditions, it is possible to change the type of the object. But it is not a sensible thing to do, and if mishandled, something strange will happen.

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.