We often encounter some inexplicable errors in Python programming. In fact, this is not a problem with the language itself, but caused by us ignoring some characteristics of the language itself. Today we will take a look at 3 incredible errors caused by using Python variables. Error, please pay more attention in future programming.
1. Variable data types are used as default parameters in function definitions
This seems right? You write a small function that, say, searches for a link on the current page and optionally appends 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 looks like very normal Python code. In fact, it is, and it can run. However, there is a problem. If we provide a list to the add_to parameter, it will work as we expect. But if we let it use the default value, something magical happens.
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 a 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 exactly what we thought. To get this result, the correct way is:
def fn(var1, var2=None): ifnot var2: var2 =[] var2.append(var1)
Or in the first example:
def search_for_links(page, add_to=None): ifnot 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 every List instantiation occurs every time the function is run. Please note that for immutable data types, such as tuples, strings, and integers, this situation does not need to be considered. This means that code like the following is very feasible:
def func(message="my message"): print(message)
2. Variable data types as class variables
This is very similar to the last error 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 URLs. When we call the add_url method, it adds a given URL to the storage. Looks pretty right 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.pythontab.com') print(b.urls) print(a.urls)
Result:
['http://www.google.com','http://www.pythontab.com'] ['http://www.google.com','http://www.pythontab.com']
Wait, what’s going on? ! That's not what we thought. We instantiate two separate objects a and b. Give one URL to a and another to b. How come these two objects have these two URLs?
This is the same problem as the first error example. When the class definition is created, the URL list is instantiated. All instances of this class use the same list. There are times when this is useful, but most of the time you don't want to do it. You want a separate storage for each object. 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 the object is created, the URL list is instantiated. When we instantiate two separate objects, they will each use two separate lists.
3. Variable allocation error
This problem has troubled me for a while. Let's make some changes and use another mutable data type - a dictionary.
a ={'1':"one",'2':'two'}
Now, suppose we want to use this dictionary elsewhere and keep its original data intact.
b = a b['3']='three'
Simple, right?
Now, let’s look at the original dictionary a that we don’t want to change:
{'1':"one",'2':'two','3':'three'}
Wow wait a minute, let’s look at b?
{'1':"one",'2':'two','3':'three'}
Wait, what? A bit messy... Let's back up and see what happens in this case with other immutable types, 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 exactly happened in the previous example? When using a mutable type, it behaves somewhat like a pointer in C. In the above code, we let b = a, what we really mean is: b becomes a reference of a. They all point to the same object in Python memory. Sound familiar? That's because this question is similar to the previous one.
Does the same thing happen with lists? Yes. So how do we solve it? This must be done very carefully. If we really need to copy a list for processing, we can do this:
b = a[:]
This will loop through and copy the reference of 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 again, not a complete copy.
Suppose you make a list on a piece of paper. In the original example, it is equivalent to A and B looking at the same piece of paper. If one person modifies this listing, both people will see the same changes. When we copy the references, everyone now has their own list. However, we assume that this list includes places to find food. If "refrigerator" is first in the list, even if it is copied, the entries in both lists will point to the same refrigerator. Therefore, if the refrigerator is modified by A and eats the big cake inside, B will also see the disappearance of the cake. There's no easy way around it. Just remember it and write your code in a way that doesn't cause this problem.
字典以相同的方式工作,并且你可以通过以下方式创建一个昂贵副本:
b = a.copy()
再次说明,这只会创建一个新的字典,指向原来存在的相同的条目。因此,如果我们有两个相同的列表,并且我们修改字典 a 的一个键指向的可变对象,那么在字典 b 中也将看到这些变化。
可变数据类型的麻烦也是它们强大的地方。以上都不是实际中的问题;它们是一些要注意防止出现的问题。在第三个项目中使用昂贵复制操作作为解决方案在 99% 的时候是没有必要的。
The above is the detailed content of Introduction to common mistakes in using Python variables. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.