python的编码规范【摘】

模块名:
小写字母,单词之间用_分割
ad_stats.py

包名:
和模块名一样

类名:
单词首字母大写
AdStats
ConfigUtil

全局变量名(类变量,在java中相当于static变量):
大写字母,单词之间用_分割
NUMBER
COLOR_WRITE

普通变量:
小写字母,单词之间用_分割
this_is_a_var

实例变量:
以_开头,其他和普通变量一样
_price   
_instance_var


普通函数:
和普通变量一样:
get_name()
count_number()
ad_stat()

私有函数(外部访问会报错):
以__开头(2个下划线),其他和普通函数一样
__get_name() 这里有人建议一个下划线,有人建议两个下划线。下面得到一个答复觉得比较有说服力一些:

“在python中定义私有变量只需要在变量名或函数名前加上 "__" (两个下划线),那么这个函数或变量就会成为私有的了。在内部,python使用一种 name mangling 技术,将__membername替换成 _classname__membername,所以你在外部使用原来的私有成员的名字时,会提示找不到。”

“无论是单下划线还是双下划线开头的成员,都是希望外部程序开发者不要直接使用这些成员变量和这些成员函数,只是双下划线从语法上能够更直接的避免错误的使用,但是如果按照 _类名__成员名 则依然可以访问到。单下划线的在动态调试时可能会方便一些,只要项目组的人都遵守下划线开头的成员不直接使用,那使用单下划线或许会更好。”


1. Comparisons to singletons like None should always be done with is or is not, never the equality operators.

Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

2. When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.

For example, use:

try:
    import platform_specific_module
except ImportError:
    platform_specific_module = None

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

3. For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq:
     if seq:

No: if len(seq)
    if not len(seq)

4. Context managers should be invoked through separate functions or methods whenever they do something other than acquire and release resources. For example:

Yes:

with conn.begin_transaction():
    do_stuff_in_transaction(conn)

No:

with conn:
    do_stuff_in_transaction(conn)

The latter example doesn't provide any information to indicate that the __enter__ and __exit__ methods are doing something other than closing the connection after a transaction. Being explicit is important in this case.

5. Don't compare boolean values to True or False using ==.

Yes:   if greeting:
No:    if greeting == True:
Worse: if greeting is True:

摘自:

http://luochunfeng163.blog.163.com/blog/static/167009249201362453358567/

http://www.cnblogs.com/ToDoToTry/archive/2012/11/27/python_naming_conventions.html

http://www.educity.cn/wenda/354157.html

原文地址:https://www.cnblogs.com/linyx/p/4716140.html