Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the three mistakes to avoid when learning to program with Python

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail what are the three mistakes to be avoided when learning to program with Python. The content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

These mistakes can cause troublesome problems that can take hours to solve.

It's not easy to admit a mistake when you do something wrong, but making a mistake 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 prevent new Python programmers from making the same mistakes, here are three mistakes I made when learning Python. These mistakes are either something I have often made for a long time, or they have caused trouble that will take several hours to solve.

Young programmers should be aware that these mistakes will be a waste of the afternoon!

1. Variable data types are used as default parameters in function definitions.

Does that seem right? You write a small function, for example, to search for a link on the current page and optionally attach 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 face of it, this looks like perfectly normal Python code, but in fact it is, and it works. But there is a problem. If we provide a list for the add_to parameter, it will work as we expected. But if we let it use the default value, something magical will happen.

Try the following code:

Def fn (var1, var2= []): var2.append (var1) print var2 fn (3) fn (4) fn (5)

Maybe you think we're going to 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, the list is instantiated as part of the function definition. When a function runs, it is not instantiated every time. This means that this function will always use exactly the same list object unless we provide a new object:

Fn (3, [4]) [4,3]

The answer is just as we thought. The right way to get this result is:

Def fn (var1, var2=None): if not var2: var2= [] var2.append (var1)

Or in the case of * *:

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 removes the instantiated content when the module is loaded so that list instantiation occurs each time the function is run. Note that you don't need to consider this for immutable data types, such as tuples, strings, and integers. This means that code like this is very feasible:

Def func (message= "my message"): print message

2. Variable data types as class variables

This is very similar to the mistake mentioned above. Consider the following code:

Class URLCatcher (object): urls = [] def add_url (self, url): self.urls.append (url)

This code looks perfectly normal. We have an object that stores URL. When we call the add_url method, it adds a given URL to the store. Doesn't that look right? Let's see what it actually looks like:

A = URLCatcher () a.add_url ('http://www.google.com') b = URLCatcher () b.add_url (' http://www.bbc.co.hk'))

B.urls:

['http://www.google.com',' http://www.bbc.co.uk']

A.urls:

['http://www.google.com',' http://www.bbc.co.uk']

Wait, what's going on?! That's not what we were thinking. We instantiated two separate objects an and b. Give one URL to an and the other to b. How can both objects have these two URL?

This is the same problem as the wrong example. When you create a class definition, the URL list is instantiated. All instances of this class use the same list. Sometimes this is useful, but most of the time you don't want to do it. You want each object to have a separate storage. 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)

Now, when you create an object, the URL list is instantiated. When we instantiate two separate objects, they will use two separate lists.

3. Variable allocation error

This problem has been bothering me for some time. Let's make some changes and use another variable data type-a dictionary.

A = {'1percent: "one",' 2percent: 'two'}

Now, suppose we want to use this dictionary somewhere else and keep its initial data intact.

B = a b ['3'] = 'three'

Easy, isn't it?

Now, let's look at the original dictionary a that we don't want to change:

{'1percent: "one",' 2percent: 'two',' 3percent: 'three'}

Wait a minute, let's take another look at b?

{'1percent: "one",' 2percent: 'two',' 3percent: 'three'}

Wait, what? It's a little messy... Let's recall 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 mutable types, it behaves a bit like a pointer to the C language. In the above code, we make b = a, and what we really mean is that b becomes a reference to a. They all point to the same object in Python memory. Sound familiar? That's because the problem is similar to the previous one. In fact, this article should be called "variable trouble".

Will the same thing happen to the list? Right. So how do we solve it? You have to be very careful. If we really need to copy a list for processing, we can do this:

B = a [:]

This will traverse and copy the reference to each object in the list and place it in a new list. But be careful: if each object in the list is mutable, we will get a reference to them again, rather than a complete copy.

Suppose you make a list on a piece of paper. In the original example, An and B are looking at the same piece of paper. If someone changes the list, both will see the same change. When we copy the reference, everyone now has their own list. However, we assume that the list includes places to find food. If the "refrigerator" is the * 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 An and eats the big cake inside, B will also see the cake disappear. There is no easy way to solve it. As long as you remember it and write code in a way that won't cause the problem.

Dictionaries work 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 already exists. So if we have two identical lists and we modify the mutable object pointed to by a key in dictionary a, we will see these changes in dictionary b as well.

The trouble with variable data types is also where they are powerful. The above are not practical problems; they are problems that we should pay attention to prevent. Using expensive replication operations as a solution in the third project is unnecessary 99% of the time. Maybe your program should be changed, so in * cases, these copies are not even needed.

On learning to use Python programming to avoid what the three mistakes are shared here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report