Familiar with Python, including variables and reference objects
In the lecture "always powerful functions", I have briefed the readers on the variables, and we have been using the variables all the time, each operation requires a value assignment. This article mentions these two things again, that is, to let the viewer have a clear understanding of the variables and values. Of course, whether or not I can achieve this goal is easy to understand. If you do not understand, it means that what I said is not good enough. You can contact me and I will help you.
Variables and objects
In the book learning python, the author describes the relationships between variables, objects, and references very clearly. I am inspired by him to a large extent. Thanks to Mr. Mark Lutz.
Apply one of the concepts in learning python: variables have no type and objects have types.
In python, if you want to use a variable, you do not need to declare it in advance. You only need to assign a value to the variable when using it. It is particularly emphasized that a variable must be assigned a value.
So, it won't work like this.
Copy codeThe Code is as follows:
>>> X
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
NameError: name 'X' is not defined
Repeated reminders: Be sure to check the error message. If a variable is written without a value assignment, python considers that the variable is not defined. Assign values not only to a non-empty value, but also to a null value.
Copy codeThe Code is as follows:
>>> X = 3
>>> Lst = []
>>> Word = ""
>>> My_dict = {}
In the previous article, I proposed an analogy that variables are connected to objects through a line (an int/list may be specific). This analogy is accepted by many people, it is the first one I have ever created. A variable can be interpreted as an element of a system table and has a namespace pointing to an object. It's too serious. If you don't understand it, just understand my analogy. A variable is something that exists in the system. It has the ability to connect to an object with a line and phishing.
What about objects? Expand your imagination. In the memory of the machine, the system allocates a space where the so-called objects are put, sometimes numbers and strings. If the number is put, it is int type. If the string is put, it is str type.
The next thing is that the variables mentioned above use their own capabilities to connect objects with themselves (pointers connect to object space), which is reference. After the reference is complete, the value is assigned.
Now that we see the figure above, we have a clear representation of the relationship between variables and objects. So strictly speaking, only objects (that is, data) in the memory space have types, while variables have no types. In this case, if you haven't fully understood it, let's make another analogy: variables are like phishing, and the lake is like memory. There are many fish in it, and there are all kinds of fish, they are objects. The task of a fisherman (variable) is to connect himself and the fish through the fish line in some way. There is a type of fish, such as silver carp, Crucian Carp, and octopus. (The Octopus also ran to the lake. Is it a fresh water catfish? Well, let's just put it down. Don't be honest.) A fisherman (variable) doesn't have this type. He caught different types of fish.
This metaphor is too bad. Make up your understanding. The viewer has a good metaphor. Don't forget to share it.
Can a single variable point to two objects at the same time? You must never step on two ships. What if so?
Copy codeThe Code is as follows:
>>> X = 4
>>> X = 5
>>> X
5
Variable x points to object 4 first, and then to object 5. When the latter is released, it automatically contacts the first object 4. Let's look at x again. The referenced object is 5. What about 4? Once no variable is referenced, it becomes a ghost. Python is very stingy, and it absolutely does not allow the existence of a ghost in the memory. All these things are regarded as garbage, and python has an automatic reclaim mechanism for garbage.
I found an illustration on the internet, very good, reference (Source: http://www.linuxidc.com/Linux/2012-09/69523.htm)
Copy codeThe Code is as follows:
>>> A = 100 # references variable a to object 100 in the memory space
As shown in:
Then, the operation is performed again:
Copy codeThe Code is as follows:
>>> A = "hello"
As shown in:
The 100 in the original memory was collected as garbage. In addition, this collection process is automatically completed by python, so we don't have to worry about it.
So how does python collect garbage? Someone asked this question on Quora. I think the answer is wonderful. Just make a link and read it with fun. Python (programming language): How does garbage collection in Python work?
Is and =
The principles of the above process are clarified, and we can take a further step below.
Copy codeThe Code is as follows:
>>> L1 = [1, 2, 3]
>>> L2 = l1
In this operation, the l1 and l2 variables reference an object, both of which are [1, 2, 3]. Why? If [1, 2, 3] is modified through l1 and the l2 reference object is modified, this viewpoint is confirmed.
Copy codeThe Code is as follows:
>>> L1 [0] = 99 # change the object to [, 2, 3]
>>> L1 # changed
[99, 2, 3]
>>> L2 # actually changed bytes.
[99, 2, 3]
Another method:
Copy codeThe Code is as follows:
>>> L1 = [1, 2, 3]
>>> L2 = [1, 2, 3]
>>> L1 [0] = 99
>>> L1
[99, 2, 3]
>>> L2
[1, 2, 3]
L1 and l2 seem to point to the same object [1, 2, 3]. In fact, in memory, these two items are irrelevant. The content is the same. It's like a long mackerel in the water. Two people caught it, but not the same one. Therefore, l2 does not change after the referenced object is modified through l1.
We can further test this problem:
Copy codeThe Code is as follows:
>>> L1
[1, 2, 3]
>>> L2
[1, 2, 3]
>>> L1 = l2 # two equal, that is, the same content
True
>>> L1 is l2 # is to compare the addresses of the two referenced objects in the memory.
False # The preceding test has already been described.
>>> L3 = l1 # By the way, the same object of the l3 and l1 applications
>>> L3
[1, 2, 3]
>>> L3 = l1
True
>>> L3 is l1 # is returns True.
True
Some objects include the copy function. Will the objects obtained through this function be new or referenced to the same object? You can also do an experiment similar to the above. For example:
Copy codeThe Code is as follows:
>>> L1
[1, 2, 3]
>>> L2 = l1 [:]
>>> L2
[1, 2, 3]
>>> L1 [0] = 22
>>> L1
[22, 2, 3]
>>> L2
[1, 2, 3]
>>> Adict = {"name": "qiwsir", "web": "qiwsir. github. io "}
>>> Bdict = adict. copy ()
>>> Bdict
{'Web': 'qiwsir. github. io ', 'name': 'qiwsir '}
>>> Adict ["email"] = "qiwsir@gmail.com"
>>> Adict
{'Web': 'qiwsir. github. io ', 'name': 'qiwsir', 'email ': 'qiwsir @ gmail.com '}
>>> Bdict
{'Web': 'qiwsir. github. io ', 'name': 'qiwsir '}
However, you should be careful when reading the official website. python doesn't always play cards in the way described above, for example, when using a small number
Copy codeThe Code is as follows:
>>> X = 2
>>> Y = 2
>>> X is y
True
> X = 200000
>>> Y = 200000
>>> X is y # What is the principle? When a small number is used, it will be cached.
False
>>> X = 'hello'
>>> Y = 'hello'
>>> X is y
True
>>> X = "what is your name? "
>>> Y = "what is your name? "
>>> X is y # not only small numbers, but also short strings
False
Is the assignment simply an equal sign? From the above, = is used to point the variable pointer to an object. However, you can go deeper. Go.
How can I get the name of a variable referenced by myself in python?
It seems that all references cannot be implemented. It seems that only the number of references is recorded internally.
In order not to cause memory leakage, python should not allow you to change the reference count.
Well, it seems that you can only use C to rewrite the part you want to improve.
Variable or function problems in python
It seems that it is difficult to call function f () for any change to variable X. The call process usually occurs when the value of and read the variable X; if a variable is assigned a certain type of structure, such as list, processing the elements in the list cannot cause a call.
1. You can use the class property to implement
2. yield syntax can be used for implementation.
File file2.py:
Import file1
X = file1.joinf ()
X. X = 90 or m = x. X, different programs can be executed.
==========================================================
File file1.py:
Def ART (func ):
Return property (** func ())
Class joinf ():
Def _ init _ (self ):
Self. _ X = None # The place where variables are actually saved and cannot be accessed directly
@ ART
Def X ():
Def fget (self): # The function called when m = x. X is executed
Pass # any commands and functions can be executed here-function f () can be called here ()
Return self. _ X # the original value is not necessarily returned. What is returned here, and what is obtained by m?
Def fset (self, value): # The function executed when the x. X = 90 operation is executed. The value is 90.
Pass # any commands and functions can be executed here-function f () can be called here ()
Self. _ X = value # If the original value is not necessarily paid to self. _ X, the value can be processed before being assigned to the value.
Return locals ()