Some programming suggestions for beginners of Python

Source: Internet
Author: User
Some programming suggestions for beginners of Python are that Python is a very expressive language. It provides us with a huge standard library and many built-in modules to help us quickly complete our work. However, many people may be lost in the functions it provides, cannot make full use of the standard library, excessive emphasis on single-line scripts, and misunderstanding of the basic structure of Python. This article is an incomplete list of some traps that beginners may fall.

1. do not know the Python version

This is a problem that occurs repeatedly on StackOverflow. Many people can write code that works perfectly on a specific version, but install different versions of Python on their own systems. Make sure that you know the Python version you are using.

You can view the Python version through the following code:

[pythontab@testServer]$ python --versionPython 2.7.10[pythontab@testServer]$ python --VPython 2.7.10

The above two methods are acceptable.

2. skip version manager

Pyenv is an excellent tool for managing different Python versions, but unfortunately it only works on * nix systems. On Mac, you can simply install it through brew install pyenv. on Linux, there is also an automatic installation program.

3. indulge in a program

Many people are keen on the excitement of a program. Even if their one-line solution is less efficient than a multi-line solution, they boast.

In Python, a row of programs essentially means 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))]

Honestly, I fabricated the above example. But I see many people write similar code. Such code becomes hard to understand in a week. If you want to do something slightly complex, such as simply adding an element to a list or set based on conditions, you may make mistakes.

Single-line code is not an achievement. Yes, they may seem flexible, but not an achievement. Imagine that it is like stuffing everything into your closet while you are cleaning the room. Good code should be clean, easy to read, and efficient.

4. use the wrong method to initialize a set

This is a more subtle issue and may surprise you. Set derivation is like list derivation.

 >>> { 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 })

The above is an example of the set derivation. A set is like a list and a container. The difference is that there cannot be any duplicate values in a collection, and they are unordered. People often mistakenly think that {} can initialize an empty set. But it does not actually initialize an empty Dictionary.

>>> {}{}>>> type({})

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

>>> set()set()>>> type(set())

Note that an empty set is expressed in combination with set (), but a set containing some elements must be represented in curly brackets.

>>> s = set()>>> sset()>>> s.add(1)>>> s{1}>>> s.add(2)>>> s{1, 2}

This is the opposite of intuition, because you expect something similar to set ([1, 2.

5. misunderstanding GIL

GIL (Global interpreter lock) means that only one thread can be running at any time point in the Python program. This means that when we create a thread and want it to run in parallel, it will not. The actual task of the Python interpreter is to quickly switch between different running threads. However, this is just a simple explanation of what actually happens, and the actual situation is much more complicated. There are many types of parallel running instances, such as various libraries that are essentially C-extended. But it does not execute Python code in parallel most of the time. In other words, the threads in Python are not like those in Java or C ++.

Many people will try to justify Python, saying that these are real threads. This is true, but it cannot change the fact that the way Python processes Threads is different from what you expect. The Ruby language also has the same situation (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 coverage of fork. However, the fork process is much more expensive than a thread, so you may not see performance improvement every time, because different processes need to do a lot of work to coordinate with each other.

However, this problem does not exist in every Python implementation version. For example, a Python implementation of PyPy-stm tries to get rid of GIL (not yet stable ). The Python implementation on other platforms, such as JVM (Jython) or CLR (IronPython), has no problems with GIL.

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

6. use legacy classes

In Python 2, there are two types of classes: "old" class and "new" class. If you use Python 3, you use the "new" class by default. To ensure that the "new" class is used in Python2, you need to make every new class you create inherit the object class, and the class cannot inherit the built-in type, such as int or list. In other words, if your base class and class do not inherit other classes, they always need to inherit the object class.

class MyNewObject(object):# stuff here

These "new" classes solve the fundamental defects of some old classes, for details about new and old classes, see _ new _ and _ init __, new and classic classes in python2.

7. iterate in the wrong way

For beginners of this language, the following code is very common:

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

In the above example, there is no need to call the len function, because list iteration is actually much simpler:

for name in names:print(name)

There are also a bunch of other tools to help you simplify iteration. For example, you can use zip to traverse two lists at the same time:

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

If you want to consider both the index and value of the list variables, you can use enumerate:

   for index, cat in enumerate(cats):print(cat, index)

There are also many useful functions in itertools for you to choose from. However, please note that using the itertools function is not always the correct choice. If a function in itertools provides a very convenient solution to the problem you are trying to solve, such as flattening a list or creating an arrangement of its content based on the given list, use it. But don't adapt to a part of your code just because you want it.

Problems caused by misuse of itertools occur too frequently, so that a highly respected Python contributor on StackOverflow has contributed an important part of their data to solve these problems.

8. use variable default parameters

I have seen the following code multiple times:

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

Never use a variable default parameter. you can use the following code instead:

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

Rather than explaining what the problem is, it is better to show the impact of using variable default parameters:

>>> 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]

The same variable c is repeatedly referenced in every function call. This may have some unexpected consequences.

Summary

These are just some problems that people who are new to Python may encounter. However, please note that the possible problems are far from that. However, another drawback is that people use Python like Java or C ++ and try to use Python in the way they are familiar with it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.