When you do something wrong, acknowledging mistakes is not an easy task, but making mistakes is part of any learning process, whether it's learning to walk or learning a new programming language, such as learning Python.
In order to let beginner Python programmers avoid the same mistakes, here are three errors I made when learning Python. These mistakes are either often made by me for a long time or caused troubles that take hours to resolve.
Young programmers have to pay attention, these mistakes will waste an afternoon!
This seems to be correct? You wrote a small function, such as searching for a link on the current page, and optionally attaching it to another provided list.
Def search_for_links(page, add_to=[]):
New_links = page.search_for_links()
Add_to.extend(new_links)
Return add_to
On the surface, this is like a very normal Python code, in fact it is, and it is operational. However, there is a problem here. If we provide a list for the add_to parameter, it will work as we expected. However, if we let it use the default value, there will be some magical things.
Try the following code:
Def fn(var1, var2=[]):
Var2.append(var1)
Print var2
Fn(3)
Fn(4)
Fn(5)
Maybe you think we will see:
[3]
[4]
[5]
But in fact, what we see is:
[3]
[3, 4]
[3, 4, 5]
why? As you can see, the same list is used every time. Why is the output like this? In Python, when we write such a function, this list is instantiated as part of the function definition. When the function runs, it is not instantiated every time. This means that this function will always use the exact same list object unless we provide a new object:
Fn(3, [4])
[4, 3]
The answer is as we think. The correct way to get this result is:
Def fn(var1, var2=None):
If not var2:
Var2 = []
Var2.append(var1)
Or in the first example:
Def search_for_links(page, add_to=None):
If not add_to:
Add_to = []
New_links = page.search_for_links()
Add_to.extend(new_links)
Return add_to
This will remove the instantiated content when the module is loaded so that list instantiation occurs every time the function is run. Note that for immutable data types, such as tuples, strings, and integers, this is not a concern. This means that code like the following is very feasible:
Def func(message=“my messageâ€):
Print message
2, variable data type as a class variableThis is very similar to the last mistake mentioned above. Consider the following code:
Class URLCatcher(object):
Urls = []
Def add_url(self, url):
Self.urls.append(url)
This code looks very normal. We have an object that stores the URL. When we call the add_url method, it adds a given URL to the store. Looks very correct? Let us see what it is actually:
a = URLCatcher()
A.add_url('http://')
b = URLCatcher()
B.add_url('http://')
B.urls:
['http://', ​​'http://']
A.urls:
['http://', ​​'http://']
Wait, what happened? ! We don't think so. We instantiated two separate objects a and b. Give one URL to a and the other to b. How do these two objects have these two URLs?
This is the same problem as the first mistake. When you create a class definition, the list of URLs is instantiated. All instances of this class use the same list. This is sometimes useful, but most of the time you don't want to do this. You want each object to have a separate store. To do this, we modify the code to:
Class URLCatcher(object):
Def __init__(self):
Self.urls = []
Def add_url(self, url):
Self.urls.append(url)
The URL list is now instantiated when the object is created. When we instantiate two separate objects, they will use two separate lists.
3, variable allocation errorThis problem has plagued me for a while. Let's make some changes and use another variable data type – the dictionary.
a = {'1': "one", '2': 'two'}
Now, suppose we want to use this dictionary somewhere else and keep its initial data intact.
b = a
b['3'] = 'three'
Simple?
Now let's look at the original dictionary a that we don't want to change:
'1': "one", '2': 'two', '3': 'three'}
Wow, let's take a look at b?
{'1': "one", '2': 'two', '3': 'three'}
Wait, what? It's a bit messy... let's think back and see what happens to other immutable types in this case, such as a tuple:
c = (2, 3)
d = c
d = (4, 5)
Now c is (2, 3) and d is (4, 5).
The result of this function is as we expected. So what happened in the previous example? When using a mutable type, it behaves a bit like a pointer to the C language. In the above code, we let b = a, what we really mean is: b becomes a reference to a. They all point to the same object in Python memory. Sounds familiar? That's because this problem is similar to the previous one. In fact, this article should be called "variable troubles."
Will the same thing happen in the list? Yes. So how do we solve it? This must be very careful. If we really need to copy a list for processing, we can do this:
b = a[:]
This will iterate over and copy the reference to each object in the list and put it in a new list. But be careful: if every object in the list is mutable, we will get a reference to them instead of a full copy.
Suppose you put a list on a piece of paper. In the original example, A and B are looking at the same piece of paper. If someone changes this list, both people will see the same change. When we copy references, everyone now has their own list. However, we assume that this list includes places to look for food. If the "refrigerator" is the first in the list, even if it is copied, the entries in both lists point to the same refrigerator. So, if the refrigerator is modified by A and eats the big cake inside, B will also see the disappearance of the cake. There is no easy way to solve it here. As long as you remember it and write code, use a way that doesn't cause this problem.
The dictionary works the same way, and you can create an expensive copy in the following ways:
b = a.copy()
Again, this will only create a new dictionary that points to the same entry that originally existed. So if we have two identical lists and we modify the mutable object pointed to by a key of dictionary a, then these changes will also be seen in dictionary b.
The trouble with variable data types is also a powerful place for them. None of the above are actual problems; they are some issues that need to be taken care of to prevent them from appearing. Using an expensive copy operation as a solution in the third project is not necessary at 99% of the time. Your program should probably be changed, so in the first example, these copies are not even needed.
ZGAR AZ Vape Pods 5.0
ZGAR electronic cigarette uses high-tech R&D, food grade disposable pod device and high-quality raw material. All package designs are Original IP. Our designer team is from Hong Kong. We have very high requirements for product quality, flavors taste and packaging design. The E-liquid is imported, materials are food grade, and assembly plant is medical-grade dust-free workshops.
From production to packaging, the whole system of tracking, efficient and orderly process, achieving daily efficient output. WEIKA pays attention to the details of each process control. The first class dust-free production workshop has passed the GMP food and drug production standard certification, ensuring quality and safety. We choose the products with a traceability system, which can not only effectively track and trace all kinds of data, but also ensure good product quality.
We offer best price, high quality Pods, Pods Touch Screen, Empty Pod System, Pod Vape, Disposable Pod device, E-cigar, Vape Pods to all over the world.
Much Better Vaping Experience!
ZGAR AZ Vape 5.0 Pods,ZGAR AZ Vape Pods 5.0,ZGAR AZ Vape Pods 5.0 Pod System Vape,ZGAR AZ Vape Pods 5.0 Disposable Pod Vape Systems
ZGAR INTERNATIONAL(HK)CO., LIMITED , https://www.oemvape-pen.com