首先,强烈推荐<<简明 Python 教程>> Swaroop, C. H. 著 沈洁元 译
其实,这本书里已经把python的最基本的用法,编码等等介绍的很好,这里把我用到的进行一下总结。
1. 字符串 连接 字符串数组 转义字符
Excellent Reference Link :
字符串
● 使用单引号(')
你可以用单引号指示字符串,就如同'Quote me on this'这样。所有的空白,即空格和制表符都照原样保留。● 使用双引号(")在双引号中的字符串与单引号中的字符串的使用完全相同,例如s = "What's your name?"。● 使用三引号('''或""")利用三引号,你可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双引号。例如:s = '''This is a multi-line string. This is the first line.This is the second line."What's your name?," I asked.He said "Bond, James Bond."'''转义字符
假设你想要在一个字符串中包含一个单引号('),那么你该怎么指示这个字符串?例如,这个字符串是What's your name?。你肯定不会用'What's your name?'来指示它,因为
Python会弄不明白这个字符串从何处开始,何处结束。所以,你需要指明单引号而不是字符串的结尾。可以通过 转义符 来完成这个任务。你用\'来指示单引号——注意这个反斜杠。现在你可以把字符串表示为'What\'s your name?'。另一个表示这个特别的字符串的方法是"What's your name?",即用双引号。类似地,要在双引号字符串中使用双引号本身的时候,也可以借助于转义符。另外,你可以用转义符
\\来指示反斜杠本身。值得注意的一件事是,在一个字符串中,行末的单独一个反斜杠表示字符串在下一行继续,而不是开始一个新的行。例如:
s = "This is the first sentence.\This is the second sentence."等价于"This is the first sentence. This is the second sentence."
字符串连接 Reference Link:
Python中有很多字符串连接方式,今天在写代码,顺便总结一下:
- 最原始的字符串连接方式:str1 + str2
- python 新字符串连接语法:str1, str2
- 奇怪的字符串方式:str1 str2
- % 连接字符串:‘name:%s; sex: ’ % ('tom', 'male')
- 字符串列表连接:str.join(some_list)
第一种,想必只要是有编程经验的人,估计都知道,直接用 “+” 来连接两个字符串:
-
'Jim' + 'Green' = 'JimGreen'
第二种比较特殊,如果两个字符串用“逗号”隔开,那么这两个字符串将被连接,但是,字符串之间会多出一个空格:
-
'Jim', 'Green' = 'Jim Green'
第三种也是 python 独有的,只要把两个字符串放在一起,中间有空白或者没有空白:两个字符串自动连接为一个字符串:
-
'Jim''Green' = 'JimGreen''Jim' 'Green' = 'JimGreen'
第四种功能比较强大,借鉴了C语言中 printf 函数的功能,如果你有C语言基础,看下文档就知道了。这种方式用符号“%”连接一个字符串和一组变量,字符串中的特殊标记会被自动用右边变量组中的变量替换:
-
'%s, %s' % ('Jim', 'Green') = 'Jim, Green'
第五种就属于技巧了,利用字符串的函数 join 。这个函数接受一个列表,然后用字符串依次连接列表中每一个元素:
-
var_list = ['tom', 'david', 'john']a = '###'a.join(var_list) = 'tom###david###john'
其实,python 中还有一种字符串连接方式,不过用的不多,就是字符串乘法,如:
-
a = 'abc'a * 3 = 'abcabcabc'
字符串数组
e.g.
image_name_list = np.array(["image420","image470","image532", "image580","image610","image650", "image690","image725","image780"])i = 0for element in image_name_list: #print element image_source = cv2.imread(image_source_path + "\\" + element + ".bmp",0) # \\表示单\,第一个\是转义字符。 #print image_source.shape,image_source.dtype # cut image image_new_sample = image_source[:200,:200]
2. 类,self,init
e.g.
class WoundImage: back_fore_region_contrast = 0 back_fore_region_gray_mean = 0 fore_region_stdard_daviation = 0 image_wound_mask = [] image_source = [] image_gray = [] image_array = [] image_final = [] def __init__(self, image_source,coordinate_array): # 这个方法在生成对象的时候被默认调用,相当于初始化函数。 self.image_source = image_source # Convert BGR to r,g,b b,g,r = cv2.split(self.image_source) # Convert BGR to HSV image_hue_saturation_value = cv2.cvtColor(self.image_source, cv2.COLOR_BGR2HSV) h,s,v=cv2.split(image_hue_saturation_value) # Convert BGR to gray self.image_gray = cv2.cvtColor(self.image_source, cv2.COLOR_BGR2GRAY) self.image_array = np.array([b,g,r,h,s,v]) self.coordinaArray = coordinate_array self.image_final = np.zeros(self.image_gray.shape) self.image_wound_mask = np.zeros(self.image_gray.shape) def find_most_efficient_channel(self): temp_contrast = 0 efficient_channel_flat = 0 for i in range(self.image_array.shape[0]): self.image_single_channel = self.image_array[i] self.set_contrast_standarddaviation_graymean() if self.back_fore_region_contrast > temp_contrast: temp_contrast = self.back_fore_region_contrast efficient_channel_flat = i self.image_single_channel = self.image_array[efficient_channel_flat] self.set_image_wound_mask() self.image_final = self.image_single_channel * self.image_wound_mask def set_image_wound_mask(self): kernalMean = np.ones((5,5),np.float)/25 imgMean = self.image_single_channel.copy() imgSD = self.image_single_channel.copy() cv2.filter2D(imgMean,-1,kernalMean); for i in range(2,self.image_single_channel.shape[0]-2): for j in range(2,self.image_single_channel.shape[1]-2): if (imgMean[i,j] >= self.back_fore_region_gray_mean) and (np.std(imgSD[i-2:i+2,j-2:j+2]) <= self.fore_region_stdard_daviation): self.image_wound_mask[i,j] = 1 def set_contrast_standarddaviation_graymean(self): #foreground tempFore = np.average(self.image_single_channel[self.coordinaArray[0,0,1]:self.coordinaArray[0,1,1],self.coordinaArray[0,0,0]:self.coordinaArray[0,1,0]]) #background tempBack1 = np.average(self.image_single_channel[self.coordinaArray[1,0,1]:self.coordinaArray[1,1,1],self.coordinaArray[1,0,0]:self.coordinaArray[1,1,0]]) tempBack2 = np.average(self.image_single_channel[self.coordinaArray[2,0,1]:self.coordinaArray[2,1,1],self.coordinaArray[2,0,0]:self.coordinaArray[2,1,0]]) tempBack3 = np.average(self.image_single_channel[self.coordinaArray[3,0,1]:self.coordinaArray[3,1,1],self.coordinaArray[3,0,0]:self.coordinaArray[3,1,0]]) tempBack4 = np.average(self.image_single_channel[self.coordinaArray[4,0,1]:self.coordinaArray[4,1,1],self.coordinaArray[4,0,0]:self.coordinaArray[4,1,0]]) self.back_fore_region_contrast = np.absolute(tempFore - np.average([tempBack1,tempBack2,tempBack3,tempBack4])) self.fore_region_stdard_daviation = np.std(self.image_single_channel[self.coordinaArray[0,0,1]:self.coordinaArray[0,1,1],self.coordinaArray[0,0,0]:self.coordinaArray[0,1,0]]) self.back_fore_region_gray_mean = np.average([tempFore,tempBack1,tempBack2,tempBack3,tempBack4]) print self.back_fore_region_contrast, self.back_fore_region_gray_mean, self.fore_region_stdard_daviation
注:类内部的每个方法的第一个参数都是self。
3. 编码规范
Reference Link:
Python风格规范
分号
Tip
不要在行尾加分号, 也不要用分号将两条命令放在同一行.
行长度
Tip
每行不超过80个字符
例外:
- 长的导入模块语句
- 注释里的URL
不要使用反斜杠连接行.
Python会将 , 你可以利用这个特点. 如果需要, 你可以在表达式外围增加一对额外的圆括号.
Yes: foo_bar(self, width, height, color='black', design=None, x='foo', emphasis=None, highlight=0) if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong'):
如果一个文本字符串在一行放不下, 可以使用圆括号来实现隐式行连接:
x = ('This will build a very long long ' 'long long long long long long string')
在注释中,如果必要,将长的URL放在一行上。
Yes: # See details at # http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.htmlNo: # See details at # http://www.example.com/us/developer/documentation/api/content/\ # v2.0/csv_file_name_extension_full_specification.html
注意上面例子中的元素缩进; 你可以在本文的 部分找到解释.
括号
Tip
宁缺毋滥的使用括号
除非是用于实现行连接, 否则不要在返回语句或条件语句中使用括号. 不过在元组两边使用括号是可以的.
Yes: if foo: bar() while x: x = bar() if x and y: bar() if not x: bar() return foo for (x, y) in dict.items(): ...No: if (x): bar() if not(x): bar() return (foo)
缩进
Tip
用4个空格来缩进代码
绝对不要用tab, 也不要tab和空格混用. 对于行连接的情况, 你应该要么垂直对齐换行的元素(见 部分的示例), 或者使用4空格的悬挂式缩进(这时第一行不应该有参数):
Yes: # Aligned with opening delimiter foo = long_function_name(var_one, var_two, var_three, var_four) # Aligned with opening delimiter in a dictionary foo = { long_dictionary_key: value1 + value2, ... } # 4-space hanging indent; nothing on first line foo = long_function_name( var_one, var_two, var_three, var_four) # 4-space hanging indent in a dictionary foo = { long_dictionary_key: long_dictionary_value, ... }No: # Stuff on first line forbidden foo = long_function_name(var_one, var_two, var_three, var_four) # 2-space hanging indent forbidden foo = long_function_name( var_one, var_two, var_three, var_four) # No hanging indent in a dictionary foo = { long_dictionary_key: long_dictionary_value, ... }
空行
Tip
顶级定义之间空两行, 方法定义之间空一行
顶级定义之间空两行, 比如函数或者类定义. 方法定义, 类定义与第一个方法之间, 都应该空一行. 函数或方法中, 某些地方要是你觉得合适, 就空一行.
空格
Tip
按照标准的排版规范来使用标点两边的空格
括号内不要有空格.
Yes: spam(ham[1], {eggs: 2}, [])No: spam( ham[ 1 ], { eggs: 2 }, [ ] )
不要在逗号, 分号, 冒号前面加空格, 但应该在它们后面加(除了在行尾).
Yes: if x == 4: print x, y x, y = y, xNo: if x == 4 : print x , y x , y = y , x
参数列表, 索引或切片的左括号前不应加空格.
Yes: spam(1)no: spam (1)Yes: dict['key'] = list[index]No: dict ['key'] = list [index]
在二元操作符两边都加上一个空格, 比如赋值(=), 比较(==, <, >, !=, <>, <=, >=, in, not in, is, is not), 布尔(and, or, not). 至于算术操作符两边的空格该如何使用, 需要你自己好好判断. 不过两侧务必要保持一致.
Yes: x == 1No: x<1
当’=’用于指示关键字参数或默认参数值时, 不要在其两侧使用空格.
Yes: def complex(real, imag=0.0): return magic(r=real, i=imag)No: def complex(real, imag = 0.0): return magic(r = real, i = imag)
不要用空格来垂直对齐多行间的标记, 因为这会成为维护的负担(适用于:, #, =等):
Yes: foo = 1000 # comment long_name = 2 # comment that should not be aligned dictionary = { "foo": 1, "long_name": 2, }No: foo = 1000 # comment long_name = 2 # comment that should not be aligned dictionary = { "foo" : 1, "long_name": 2, }
Shebang
Tip
大部分.py文件不必以#!作为文件的开始. 根据 , 程序的main文件应该以 #!/usr/bin/python2或者 #!/usr/bin/python3开始.
(译者注: 在计算机科学中, (也称为Hashbang)是一个由井号和叹号构成的字符串行(#!), 其出现在文本文件的第一行的前两个字符. 在文件中存在Shebang的情况下, 类Unix操作系统的程序载入器会分析Shebang后的内容, 将这些内容作为解释器指令, 并调用该指令, 并将载有Shebang的文件路径作为该解释器的参数. 例如, 以指令#!/bin/sh开头的文件在执行时会实际调用/bin/sh程序.)
#!先用于帮助内核找到Python解释器, 但是在导入模块时, 将会被忽略. 因此只有被直接执行的文件中才有必要加入#!.
类
Tip
如果一个类不继承自其它类, 就显式的从object继承. 嵌套类也一样.
Yes: class SampleClass(object): pass class OuterClass(object): class InnerClass(object): pass class ChildClass(ParentClass): """Explicitly inherits from another class already."""No: class SampleClass: pass class OuterClass: class InnerClass: pass
继承自 object 是为了使属性(properties)正常工作, 并且这样可以保护你的代码, 使其不受Python 3000的一个特殊的潜在不兼容性影响. 这样做也定义了一些特殊的方法, 这些方法实现了对象的默认语义, 包括 __new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__ .
字符串
Tip
即使参数都是字符串, 使用%操作符或者格式化方法格式化字符串. 不过也不能一概而论, 你需要在+和%之间好好判定.
Yes: x = a + b x = '%s, %s!' % (imperative, expletive) x = '{}, {}!'.format(imperative, expletive) x = 'name: %s; score: %d' % (name, n) x = 'name: {}; score: {}'.format(name, n)No: x = '%s%s' % (a, b) # use + in this case x = '{}{}'.format(a, b) # use + in this case x = imperative + ', ' + expletive + '!' x = 'name: ' + name + '; score: ' + str(n)
避免在循环中用+和+=操作符来累加字符串. 由于字符串是不可变的, 这样做会创建不必要的临时对象, 并且导致二次方而不是线性的运行时间. 作为替代方案, 你可以将每个子串加入列表, 然后在循环结束后用 .join 连接列表. (也可以将每个子串写入一个 cStringIO.StringIO 缓存中.)
Yes: items = ['
%s, %s |
%s, %s |
在同一个文件中, 保持使用字符串引号的一致性. 使用单引号’或者双引号”之一用以引用字符串, 并在同一文件中沿用. 在字符串内可以使用另外一种引号, 以避免在字符串中使用. GPyLint已经加入了这一检查.
(译者注:GPyLint疑为笔误, 应为PyLint.)
Yes: Python('Why are you hiding your eyes?') Gollum("I'm scared of lint errors.") Narrator('"Good!" thought a happy Python reviewer.')No: Python("Why are you hiding your eyes?") Gollum('The lint. It burns. It burns us.') Gollum("Always the great lint. Watching. Watching.")
为多行字符串使用三重双引号”“”而非三重单引号’‘’. 当且仅当项目中使用单引号’来引用字符串时, 才可能会使用三重’‘’为非文档字符串的多行字符串来标识引用. 文档字符串必须使用三重双引号”“”. 不过要注意, 通常用隐式行连接更清晰, 因为多行字符串与程序其他部分的缩进方式不一致.
Yes: print ("This is much nicer.\n" "Do it this way.\n")No: print """This is pretty ugly. Don't do this. """
文件和sockets
Tip
在文件和sockets结束时, 显式的关闭它.
除文件外, sockets或其他类似文件的对象在没有必要的情况下打开, 会有许多副作用, 例如:
- 它们可能会消耗有限的系统资源, 如文件描述符. 如果这些资源在使用后没有及时归还系统, 那么用于处理这些对象的代码会将资源消耗殆尽.
- 持有文件将会阻止对于文件的其他诸如移动、删除之类的操作.
- 仅仅是从逻辑上关闭文件和sockets, 那么它们仍然可能会被其共享的程序在无意中进行读或者写操作. 只有当它们真正被关闭后, 对于它们尝试进行读或者写操作将会跑出异常, 并使得问题快速显现出来.
而且, 幻想当文件对象析构时, 文件和sockets会自动关闭, 试图将文件对象的生命周期和文件的状态绑定在一起的想法, 都是不现实的. 因为有如下原因:
- 没有任何方法可以确保运行环境会真正的执行文件的析构. 不同的Python实现采用不同的内存管理技术, 比如延时垃圾处理机制. 延时垃圾处理机制可能会导致对象生命周期被任意无限制的延长.
- 对于文件意外的引用,会导致对于文件的持有时间超出预期(比如对于异常的跟踪, 包含有全局变量等).
推荐使用 以管理文件:
with open("hello.txt") as hello_file: for line in hello_file: print line
对于不支持使用”with”语句的类似文件的对象,使用 contextlib.closing():
import contextlibwith contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page: for line in front_page: print line
Legacy AppEngine 中Python 2.5的代码如使用”with”语句, 需要添加 “from __future__ import with_statement”.
TODO注释
Tip
为临时代码使用TODO注释, 它是一种短期解决方案. 不算完美, 但够好了.
TODO注释应该在所有开头处包含”TODO”字符串, 紧跟着是用括号括起来的你的名字, email地址或其它标识符. 然后是一个可选的冒号. 接着必须有一行注释, 解释要做什么. 主要目的是为了有一个统一的TODO格式, 这样添加注释的人就可以搜索到(并可以按需提供更多细节). 写了TODO注释并不保证写的人会亲自解决问题. 当你写了一个TODO, 请注上你的名字.
# TODO(kl@gmail.com): Use a "*" here for string repetition.# TODO(Zeke) Change this to use relations.
如果你的TODO是”将来做某事”的形式, 那么请确保你包含了一个指定的日期(“2009年11月解决”)或者一个特定的事件(“等到所有的客户都可以处理XML请求就移除这些代码”).
导入格式
Tip
每个导入应该独占一行
Yes: import os import sysNo: import os, sys
导入总应该放在文件顶部, 位于模块注释和文档字符串之后, 模块全局变量和常量之前. 导入应该按照从最通用到最不通用的顺序分组:
- 标准库导入
- 第三方库导入
- 应用程序指定导入
每种分组中, 应该根据每个模块的完整包路径按字典序排序, 忽略大小写.
import foofrom foo import barfrom foo.bar import bazfrom foo.bar import Quuxfrom Foob import ar
语句
Tip
通常每个语句应该独占一行
不过, 如果测试结果与测试语句在一行放得下, 你也可以将它们放在同一行. 如果是if语句, 只有在没有else时才能这样做. 特别地, 绝不要对 try/except 这样做, 因为try和except不能放在同一行.
Yes: if foo: bar(foo)No: if foo: bar(foo) else: baz(foo) try: bar(foo) except ValueError: baz(foo) try: bar(foo) except ValueError: baz(foo)
访问控制
Tip
在Python中, 对于琐碎又不太重要的访问函数, 你应该直接使用公有变量来取代它们, 这样可以避免额外的函数调用开销. 当添加更多功能时, 你可以用属性(property)来保持语法的一致性.
(译者注: 重视封装的面向对象程序员看到这个可能会很反感, 因为他们一直被教育: 所有成员变量都必须是私有的! 其实, 那真的是有点麻烦啊. 试着去接受Pythonic哲学吧)
另一方面, 如果访问更复杂, 或者变量的访问开销很显著, 那么你应该使用像 get_foo() 和 set_foo() 这样的函数调用. 如果之前的代码行为允许通过属性(property)访问 , 那么就不要将新的访问函数与属性绑定. 这样, 任何试图通过老方法访问变量的代码就没法运行, 使用者也就会意识到复杂性发生了变化.
命名
Tip
module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name.
应该避免的名称
- 单字符名称, 除了计数器和迭代器.
- 包/模块名中的连字符(-)
- 双下划线开头并结尾的名称(Python保留, 例如__init__)
命名约定
- 所谓”内部(Internal)”表示仅模块内可用, 或者, 在类内是保护或私有的.
- 用单下划线(_)开头表示模块变量或函数是protected的(使用import * from时不会包含).
- 用双下划线(__)开头的实例变量或方法表示类内私有.
- 将相关的类和顶级函数放在同一个模块里. 不像Java, 没必要限制一个类一个模块.
- 对类名使用大写字母开头的单词(如CapWords, 即Pascal风格), 但是模块名应该用小写加下划线的方式(如lower_with_under.py). 尽管已经有很多现存的模块使用类似于CapWords.py这样的命名, 但现在已经不鼓励这样做, 因为如果模块名碰巧和类名一致, 这会让人困扰.
Python之父Guido推荐的规范
Type | Public | Internal |
---|---|---|
Modules | lower_with_under | _lower_with_under |
Packages | lower_with_under | |
Classes | CapWords | _CapWords |
Exceptions | CapWords | |
Functions | lower_with_under() | _lower_with_under() |
Global/Class Constants | CAPS_WITH_UNDER | _CAPS_WITH_UNDER |
Global/Class Variables | lower_with_under | _lower_with_under |
Instance Variables | lower_with_under | _lower_with_under (protected) or __lower_with_under (private) |
Method Names | lower_with_under() | _lower_with_under() (protected) or __lower_with_under() (private) |
Function/Method Parameters | lower_with_under | |
Local Variables | lower_with_under |
Main
Tip
即使是一个打算被用作脚本的文件, 也应该是可导入的. 并且简单的导入不应该导致这个脚本的主功能(main functionality)被执行, 这是一种副作用. 主功能应该放在一个main()函数中.
在Python中, pydoc以及单元测试要求模块必须是可导入的. 你的代码应该在执行主程序前总是检查 if __name__ == '__main__' , 这样当模块被导入时主程序就不会被执行.
def main(): ...if __name__ == '__main__': main()
所有的顶级代码在模块导入时都会被执行. 要小心不要去调用函数, 创建对象, 或者执行那些不应该在使用pydoc时执行的操作.
注释
Tip
确保对模块, 函数, 方法和行内注释使用正确的风格
文档字符串
模块
函数和方法
类
块注释和行注释