Home Backend Development Python Tutorial Some programming advice for Python beginners

Some programming advice for Python beginners

Oct 17, 2016 pm 01:23 PM

Python is a very expressive language. It provides us with a huge standard library and many built-in modules to help us get our work done quickly. However, many people may get lost in the features it provides, fail to take full advantage of the standard library, place too much emphasis on one-line scripts, and misunderstand the basic structure of Python. This article is a non-exhaustive list of some of the pitfalls new Python developers can fall into.

1. Don’t know the Python version

This is a recurring question on StackOverflow. Many people can write code that works perfectly on one version, but they have a different version of Python installed on their system. Make sure you know which version of Python you are using.

You can check the Python version through the code below:

[pythontab@testServer]$ python --version
Python 2.7.10
[pythontab@testServer]$ python --V
Python 2.7.10
Copy after login

Both of the above methods are possible

2. Do not use a version manager

pyenv is an excellent tool for managing different Python versions, but Unfortunately, it only works on *nix systems. On Mac systems, you can simply install it via brew install pyenv, and on Linux, there is an automatic installer as well.

3. Addicted to one-line programs

Many people are keen on the excitement brought by one-line programs. Even if their one-line solution is less efficient than a multi-line solution, they'll brag about it.

A one-liner in Python essentially means a complex derivation with multiple expressions. For example:

l = [m for a, b in zip(this, that) if b.method(a) != b for m in b if not m.method(a, b) and reduce(lambda x, y: a + y.method(), (m, a, b))]
Copy after login

To be honest, I made up the above example. But I see a lot of people writing similar code. Code like this becomes unintelligible after a week. If you want to do something slightly more complex, such as simply adding an element to a list or set based on a condition, you're probably going to make a mistake.

Singles of code are not an achievement, yes they may look flexible, but they are not an achievement. Imagine it's like you're cleaning your house and stuffing everything into your closet. Good code should be clean, easy to read and efficient.

4. Initializing a collection in the wrong way

This is a more subtle problem that may catch you off guard. Set comprehensions are a lot like list comprehensions.

 
>>> { n for n in range(10) if n % 2 == 0 }
{0, 8, 2, 4, 6}
>>> type({ n for n in range(10) if n % 2 == 0 })
Copy after login

The above is an example of set derivation. A collection is like a list and a container. The difference is that there cannot be any duplicate values ​​in a set and it is unordered. People who see set derivation often mistakenly think that {} initializes an empty set. But it doesn't, it initializes an empty dictionary.

>>> {}
{}
>>> type({})
Copy after login

If you want to initialize an empty collection, you can simply call the set() method.

>>> set()
set()
>>> type(set())
Copy after login

Note that an empty set is represented by set(), but a set containing some elements must be represented by curly braces surrounding the elements.

>>> s = set()
>>> s
set()
>>> s.add(1)
>>> s
{1}
>>> s.add(2)
>>> s
{1, 2}
Copy after login

This is counter-intuitive because you expect something similar to set([1, 2]).

5. Misunderstanding GIL

GIL (global interpreter lock) means that in a Python program, only one thread can be running at any point in time. This means that when we create a thread and want it to run in parallel, it doesn't do that. The actual job of the Python interpreter is to quickly switch between different running threads. But this is a very simple explanation of what actually happens, which is much more complex. There are many examples of running in parallel, for example using various libraries that are essentially C extensions. But when you run Python code, most of the time it doesn't execute in parallel. In other words, threads in Python are not like threads in Java or C++.

Many people will try to defend Python by saying these are real threads. This is certainly true, but it doesn't change the fact that Python handles threads differently than you might expect. The same situation exists with the Ruby language (Ruby also has an interpreter lock).

The specified solution is to use the multiprocessing module. The multiprocessing module provides the Process class, which is a good overlay for fork. However, a fork process is much more expensive than a thread, so you may not see a performance improvement every time because a lot of work needs to be done between different processes to coordinate with each other.

However, this problem does not exist in every implementation of Python. For example, one implementation of Python, PyPy-stm, attempts to get rid of the GIL (it is still unstable). Python implementations built on other platforms, such as the JVM (Jython) or the CLR (IronPython), also have no GIL issues.

In short, be careful when using the Thread class, what you get may not be what you want.

6. Use old-style classes

在Python 2中,有两种类型的类,分别为“旧式”类和“新式”类。如果你使用Python 3,那么你默认使用“新式”类。为了确保在Python2中使用“新式”类,你需要让你新创建的每一个类都继承object类,且类不能已继承了内置类型,例如int或list。换句话说,你的基类、类如果不继承其他类,就总是需要继承object类。

class MyNewObject(object):
# stuff here
Copy after login

这些“新式”类解决一些老式类的根本缺陷,想要详细了解新式类和旧式类请参见《python新式类和旧式类区别》《python2中的__new__与__init__,新式类和经典类》。

7.按错误的方式迭代

对于这门语言的新手来说,下边的代码是非常常见的:

for name_index in range(len(names)):
print(names[name_index])
Copy after login

在上边的例子中,没有必须调用len函数,因为列表迭代实际上要简单得多:

for name in names:
print(name)
Copy after login

此外,还有一大堆其他的工具帮助你简化迭代。例如,可以使用zip同时遍历两个列表:

for cat, dog in zip(cats, dogs):
print(cat, dog)
Copy after login

如果你想同时考虑列表变量的索引和值,可以使用enumerate:

   
for index, cat in enumerate(cats):
print(cat, index)
Copy after login

在itertools中也有很多有用的函数供你选择。然而请注意,使用itertools函数并不总是正确的选择。如果itertools中的一个函数为你试图解决的问题提供了一个非常方便的解决办法,例如铺平一个列表或根据给定的列表创建一个其内容的排列,那就用它吧。但是不要仅仅因为你想要它而去适应你代码的一部分。

滥用itertools引发的问题出现的过于频繁,以至于在StackOverflow上一个德高望重的Python贡献者已经贡献他们资料的重要组成部分来解决这些问题。

8.使用可变的默认参数

我多次见到过如下的代码:

def foo(a, b, c=[]):
# append to c
# do some more stuff
Copy after login

永远不要使用可变的默认参数,可以使用如下的代码代替:

def foo(a, b, c=None):
if c is None:
c = []
# append to c
# do some more stuff
Copy after login

与其解释这个问题是什么,不如展示下使用可变默认参数的影响:

>>> def foo(a, b, c=[]):
... c.append(a)
... c.append(b)
... print(c)
...
>>> foo(1, 1)
[1, 1]
>>> foo(1, 1)
[1, 1, 1, 1]
>>> foo(1, 1)
[1, 1, 1, 1, 1, 1]
Copy after login

同一个变量c在函数调用的每一次都被反复引用。这可能有一些意想不到的后果。

总结

这些只是相对来说刚接触Python的人可能会遇到的一些问题。然而请注意,可能会遇到的问题远非就这么些。然而另一些缺陷是人们像使用Java或C++一样使用Python,并且试图按他们熟悉的方式使用Python。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

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.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

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.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python for Scientific Computing: A Detailed Look Python for Scientific Computing: A Detailed Look Apr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python for Web Development: Key Applications Python for Web Development: Key Applications Apr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

See all articles