Python--code like a pythonista:idiomatic Python

Source: Internet
Author: User

Code like a pythonista:idiomatic Python


If you have a C + + foundation, it is relatively easy to learn another language. Because C + + is process oriented and object oriented. It is very low level, can access the machine like C, it is also very advanced, there are templates, STL and so on. If I read the deep C + + object model carefully, I think other languages will not be more complicated than this. The more you know about C + +, the more code you write in other languages, the more like C + +, the less valuable the new language will be. So, learn a new language to abandon the original subconscious, including code style.

1. The Zen of Python (1)

Prettier than ugly.
Clearer than implied good
Simple is better than complicated.
Complexity is better than obscurity.
It's better to split than nest.
Loose coupling is better than tight coupling.
Readability is valuable
Special conditions are not enough to break these terms
Despite the practice of defeating the purity of theory
Mistakes never cover up
Unless it is explicitly appeased.
......

2. PEP 8:style Guide for Python

Important Style guidelines for Python

Whitespace1
    • Each level is aligned to 4 spaces
    • No hard tab
    • Never mix tabs with spaces
    • Leave 1 blank lines between functions
    • Leave 2 lines between classes blank
Whitespace 2
    • In the dictionary, list, tuple, parameter list "," followed by a space, the dictionary ":" After adding a space
    • Add a grid between an assignment or a comparison
    • Spaces are important in parentheses, and there are no spaces for function names and parentheses
    • Do not immediately space in the Docstrings
Naming
    • Joined_lower for functions, methods, properties
    • Joined_lower or All_caps for constants
    • StudlyCaps for classes, no need for front plus C
    • #每字母大写
    • CamelCase only for compatibility with existing conventions
    • Properties are: Interface,_internal, __private. But never use the latter one.

Some of the access rights from C++/java to classes are too much to care about. In python, myclass.__private resolves directly to myclass._myclass__private because it can cause "visual" access. Python has a rule: "we ' reall consenting adults here" and you have no reason to hide anything from me. Subclasses have the power to inherit attributes from the parent class, and the parent class is obliged to provide the child class with the relevant documentation to help rewrite it, rather than deny it.

Python advocates the use of _internal to represent a private property, which does not have command space restrictions, but is simply a good reminder of "being careful with this, it's an internalimplementation detail; Don ' t touch it if you don ' t fully understand it "

Long Lines &continuations

Wrap lines in parentheses use implied wrapping, but be aware of the alignment

def __init__ (self, first, second, third,        fourth, fifth, sixth):    output = (first + second + third        + Fourth + FI) Fth + Sixth)

Other line to use "\", note that there is no space behind

Longstrings

Like the C language, two adjacent strings can be automatically connected by the compiler. The difference is that in C the string has only one form, that is, "", but Python can have ', ', ' r ', ' ', ' ", and so on. But the principle is the same.

Combining statements

It is not recommended to write multiple statements on the same line in Python. such as if statements. Python is very fastidious about the structure and process of displaying code by indenting it in.

Exchange value

Tuples in Python are very interesting and are not perceived by people in the C language system.

B, A = A, b

Tuples have very good versatility, and lists and tuples can be easily exchanged

A = [45]b, c, d = a

Tuples are also often used in a for statement to process multiple indexes at once

>>> people = [L, [' Guido ', ' BDFL ', ' unlisted ']]>>> for (name, title, phone) in people: ... print name , phone
More about tuples

The most important thing about the construction of tuples is ",". For example,

>>> 1, (1,)

Even if there are no brackets above.

Interactive "_"

In the interpreter, _ is used to represent the result of the last operation. This mechanism tends to be very convenient for use!

Building String from substrings,,

This article is supposed to be popular in the Python world. '. Join () is only useful if you are overriding the For Loop connection list

colors = [' Red ', ' blue ', ' green ', ' yellow ']result = ' for s in Colors:result + = s

result = '. Join (colors) #这一条要比上面for循环更有效率

Used in Where possible

First, in is the operator, not the keyword, and second, all built-in Windows support this operator. The author would like to emphasize that inhas two commonly used positions: 1. With for execution traversal; 2. Use with if judgment exists.

The author has repeatedly emphasized that the dictionary overloaded in operation is that the object is all keys, so it is not necessary to first call D.keys () to get a list of keys, then use in, but directly with in D!

Dictionary Get Method

When adding a key to a dictionary, it is often necessary to determine whether the original key exists. The Get method works well if you just do something about the original value.

Get (Key,default): Gets the value of key and returns default if key does not exist.
Dictionary SetDefault Method

The previous section is get, then the corresponding will have settings. The semantics of SetDefault is "set if necessary, the get", which first determines whether the key exists, if it does not exist, or returns the value that already exists. In the cookbook book, it mentions that this function is useful for dictionaries with values linked to lists.

Defaultdict

It is derived from the dictionary, as the name implies, the dictionary has a default value (in fact it passes a function). The generation of this dictionary comes from simplifying SetDefault calls, and in the future when you encounter using SetDefault, consider using this special dictionary instead.

PS: This class is derived from the collections module, which also contains other useful modules, including queues, Orderedict, Mutableset, and so on.

Building Dictionary

Combine 2 sequences in a dictionary: One sequence is the key, and the other is the value. This operation has a customary method, which is to use a zip combination.

given = [' John ', ' Eric ', ' Terry ', ' Michael ']family = [' Cleese ', ' Idle ', ' Gilliam ', ' Palin ']pythons = dict (Zip (given, famil Y))
Test for Truth Values

Python does not like to compare with true or false when conditions are judged, but rather directly with built-in conversions and not. This makes the code more concise. The following is a complete table that evaluates to True and false.

False

True

False (= = 0)

True (= = 1)

"" (empty string)

Any string but "" ("", "anything")

0, 0.0

Any number but 0 (1, 0.1,-1, 3.14)

[], (), {}, set ()

Any non-empty container ([0], (None,), ['])

None

Almost any object that's not explicitly False

Index & Item:enumerate

The big feature of the enumerate function is that this is a generator function, so the efficiency will be good on some occasions. This function should be the most used when it comes to index. Because of the innate flaw of the For loop in the Python language, if you want to achieve this effect, you must use range and then the index. Just because of this flaw, this function is produced! It makes me feel like STL. Many people recommend using iterators to traverse, some people think that the statement is too lengthy, so the c++0x introduced an auto keyword.

Default Parameter Values

At first there was a very confusing code

def bad_append (New_item, a_list=[]): A_list.append (New_item) return a_list
>>> Print bad_append (' one ') [' One ']>>> print bad_append (' one ') [' One ', ' both ']

The problem is that a_list is a variable that is defined as an empty list at the time of declaration. And list is the Mutable object ~~~~~~~~~~

The reason I finally found it. When the function is declared, an empty list (' [] ') is created, and A_list is simply the label of the empty list. In the compiler, A_list is killed as the address "reference" for a global list. At the first call to append (' on '), the empty list becomes [' one '] and the list is not recycled after the function exits, so this happens on the next call!

Advanced% String Formatting

% has a very interesting usage, which is to write out the object name within the string.

Values = {' name ': Name, ' Messages ': messages}print (' Hello% (name) s, you have% (messages) I '% values)

The advantage of this notation is that when you want to change the print format, you just need to change the contents of the content. In general, values are replaced with locals (), which makes this flexible mechanism very powerful. For example, you can pass a string to a function to specify what is printed.

Generator expression (generator-expressions)

GE is very similar to listcomprehension (list resolution)

List resolution:
Syntax: [Expr for Iter_var in iterable] or [expr for Iter_var in iterable ifcond_expr]

Generator expression:
Syntax: (expr for Iter_var in iterable) or (expr for iter_var in iterable if cond_expr)

The generator expression is a little later than the list parsing, and its benefits are obvious, which is that it returns a "generator" rather than a list.

The generator is recommended in Python instead of the regular for loop, and many local generators can be substituted, because they support the same degree in nature. When the list is used only as a temporary use, the generator may perform better in memory.

Reading Lines from Text/data File

Please look at the code

datafile = open (' datafile ') for line in datafile:do_something (line)

Probably a lot of people will use the ReadLines method, for small files, there is no difference between the two, but large files the former efficiency is much higher.

Python--code like a pythonista:idiomatic Python

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.