Details about the dynamic types of python advanced tutorials and python advanced tutorials

Source: Internet
Author: User

Details about the dynamic types of python advanced tutorials and python advanced tutorials

Dynamic typing is another important core concept of Python. As we have said before, Python variables do not need to be declared. When assigning values, variables can be assigned to any value again. These are related to the concept of dynamic types.

Dynamic type

Among the objects we contact, there is a special type of object used to store data. Common objects of this type include numbers, strings, tables, and dictionaries. In C, we call such data structures as variables. In Python, these are objects.

An object is an object stored in the memory. However, we cannot directly access this object. The object name written in the program only points to the reference of this object ).

Separation of references and objects is the core of dynamic types. A reference can point to a new object at any time:
Copy codeThe Code is as follows:
A = 3
A = 'at'

In the first statement, 3 is an integer object stored in the memory. By assigning values, reference a to object 3.

In the second statement, The 'at' object created in the memory is a string ). Reference a points to 'at '. In this case, object 3 no longer points to it. Python will automatically destroy the objects (destruct) that are not referenced to release the corresponding memory.

(For small integers and short strings, Python caches these objects instead of frequently creating and destroying them .)
Copy codeThe Code is as follows: a = 5
B =
A = a + 2
Let's look at this example. In the first two sentences, let a and B point to the same integer object 5 (B = a means that B points to the object referenced by ). However, the third sentence actually re-assigns a value to reference a and points a to a new object 7. In this case, a and B point to different objects respectively. We can see that even if multiple references point to the same object, if a reference value changes, it actually points to a new reference without affecting other references. In terms of effect, each reference is independent of each other and does not affect each other.

The same is true for other data objects:
Copy codeThe Code is as follows:
L1 = [1, 2, 3]
L2 = L1
L1 = 1

Note the following:
Copy codeThe Code is as follows:
L1 = [1, 2, 3]
L2 = L1
L1 [0] = 10
Print L2

In this case, we no longer assign values to the reference L1, but assign values to the elements of the table pointed to by L1. The result is that L2 also changes.

Why? Because L1 and L2 points to the table that has not changed. A table actually contains multiple referenced objects (each reference is an element, such as L1 [0], L1 [1]..., each reference points to an object, such as 1, 2, 3 ),. The value assignment operation L1 [0] = 10 does not change L1's point, but instead changes L1 [0], that is, a part of the table object (an element ), so all references to this object are affected.

(In contrast, our previous assignment operations did not affect the object itself, but changed the reference point .)

The list can reference its elements to change the object itself (in-place change ). This type of object is called a mutable object. The dictionary is also of this type.

Like the previous numbers and strings, the object itself cannot be changed, but the reference point can only be changed, called immutable object ).

The previously learned tuple can call referenced elements but cannot assign values. Therefore, it cannot change the object itself, so it is also an immutable object.

View function parameter transfer from dynamic type

The parameter transfer of a function is essentially a reference. For example:

Copy codeThe Code is as follows:
Def f (x ):
X = 100
Print x

A = 1
F ()
Print

Parameter x is a new reference pointing to the object referred to by. If the parameter is an immutable object, a and x references are independent of each other. The operation on parameter x does not affect reference. This transfer is similar to the value transfer in C.

If mutable objects are passed, changing the function parameters may change the original object. All references pointing to the original object will be affected, so pay attention to this issue during programming. For example:

Copy codeThe Code is as follows:
Def f (x ):
X [0] = 100
Print x

A = [1, 2, 3]
F ()
Print

Dynamic types are one of the core mechanisms of Python. You can familiarize yourself with the application.

Summary

Separation of references and objects. An object is an entity that stores data in the memory. A reference points to an object.

Mutable object

Function value transfer


How to Implement Dynamic functions in python classes?

Here is an example of dynamically adding class functions.
Declare a class. When the class is initialized, read the configuration file and load the function under the module under the specified directory according to the configuration list. The function and the module have the same name, dynamically load this function as a member function of the class.
The Code is as follows:
Class WinBAS (Bas ):
Def _ init _ (self ):
Self. _ baslist = {}
Self. _ Init_Modules ()
Pass
Def _ Init_Modules (self ):
Import modplugs
For m in modplugs. _ moduleset __:
Mh = _ import _ ('Les Les. '+ m) # +'. '+ m)
Ma = getattr (mh, m) # + '.' + m)
Ma = getattr (ma, m)
Setattr (self. _ class __, m, ma)
Modplugs. py is the module configuration file as follows:
_ Moduleset _ = [
'Bas _ getuserlist ',
]
Create an empty _ init _ under the modules directory __. py file to change the Directory into a package, and create a real BAS_GetUserList under the modules directory. The BAS_GetUserList function in the BAS_GetUserList file is as follows:
Def BAS_GetUserList (self, strs ):
Return [0, strs]

In this way, the WinBAS class can dynamically Add the BAS_GetUserList function.

What should I do if I want to dynamically create objects in python?

Class BaseObject (object ):
Def _ init _ (self, ** kwg ):
Self. _ dict _ = dict (kwg)

Content = ''' Tim. Wang | M | 43
Bruce. Wang | M | 38
Amay. Song | F | 21 '''

Def ln2obj (ln ):
Name, sex, age = ln. split ('| ')
Return BaseObject (name = name, sex = sex, age = int (age ))

Students = map (ln2obj, content. splitlines ())

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.