一,语句的结束
- 每一句逻辑行的结束都是以物理行的结束为结束。如果逻辑行想链接两行物理行,请使用“\”,但值得注意的是,他只能用来链接代码而不是能链接两行注释或字符串,如:
<code>if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1
- 但是括号内的内容,不需要使用反斜杠也可以链接多行,如:
<code>month_names = ['Januari', 'Februari', 'Maart', # These are the 'April', 'Mei', 'Juni', # Dutch names 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year
二,如何定义一个函数或者方法
use "def" to definition fuction
三,一个*号和两个的区别
<code>2*3 表示2乘以3 2**3表示2的立方
四,缩进——代码格式
java通过括号来界定一段代码,而python使用缩进做为代码段的界定。空格和tabs都可以用来作为缩进,但最好不要混用。如:
<code>def perm(l): # Compute the list of all permutations of l if len(l) <= 1: return [l] r = [] for i in range(len(l)): s = l[:i] + l[i+1:] p = perm(s) for x in p: r.append(l[i:i+1] + x) return r
五,字符串连接
用引号扩起来的两个相邻字符串,实际意义表示为他们两相连的那个字符串。且这两个字符串的引号可以不同,例如:
<code>"hello" 'world' is equivalent to "helloworld".
六,数据结构
在python中所有数据类型都是对象,比如int、和string。这同java不一样,java中int是原始本地类型(primitive native types)
6.1 list和tuble的区别
- list是用方括号括起来的,成员之间通过逗号分割的表示方式。tuble是用小括号(小括号可选)扩起来,成员直接用逗号分割。
- list是可变的,可以进行增删改,tuble如其名一样,作为元组他们是不变的
6.2 dictionary
dictionary有点类似java中的map。dictionary的key必须是唯一且不可修改的值,比如string,但其映射的value可以是可变的值,如list,解读的意思,就是key值必须取基本类型,比如int和string,因为基本类型都是不可变的。dictionary的格式有点像json
6.3 sequence
6.3.1 定义
sequence特指那些具有顺序的数据类型,所以前面介绍的list、tuple、string都属于sequence类型
6.3.2 用法
6.3.2.1 索引取值
使用方括号加数字表示取sequence的具体某位置的值,如:[2]
6.3.2.2 子sequence截取
使用方括号加冒号的方式表示取子sequence,冒号是必须的,两边的数字可选,取值方式为左开右闭,如:[2:3]
<code>值得说明的是,截取的子sequence是一个完全新的对象,所以如果不指定数字,而直接使用[:]来截取,相当于对原sequence复制了一份新的对象
使用两个冒号时,第三个数字指定截取时的步长,如:[2:3:1]
6.4 Set
无序的对象集合,原理和操作方式同java类似
6.5 References
声明一个变量,并给他赋值。实际上是把对象的引用赋给了这个变量。多一个变量可以指向同一个对象。引用的概念同java类似
七,编程方式
7.1 面向过程编程
python支持面向过程编程风格,就像c一样,定义方法,定义变量。程序的组织方式是通过过程块来组织
7.2 面向对象编程
python同时也支持面向对象编程风格,就像java一样。类来组织程序块,类中可以定义函数,变量,类中的函数叫做方法。类中的变量和方法统称为类的属性
属于每一个实例的变量叫做实例变量
只属于类的变量叫做类变量
7.2.1 self
类似java中this引用,指代当前对象。类中的方法其必须都要有一个参数,这个参数就是self,用来指代调用该方法的当前对象,当然调用该方法时不用显示写出这个参数,python自己提供
7.2.2 类定义
一个简单的类定义如下:
<code>__author__ = 'vincentc' class Person : pass p = Person() print(p)
7.2.3 定义类方法示例
<code>__author__ = 'vincentc' class Person: def sayHi(self): #每个类方法,都必须定义的默认参数,指代调用该方法的当前对象,名字约定俗成为self,最好沿用这个。该方法在调用时,不用显示指定该参数,有python默认提供 print('Hello,how are you') p = Person() p.sayHi()
7.2.4 初始化方法(__init__)
__init__方法用来在创建对象时,初始化一些数据,同java的构造方法类似,示例如下:
<code>__author__ = 'vincentc' class Person: def __init__(self,name): self.name = name def sayHi(self): print('Hello,my name is',self.name) p = Person('Vincent') p.sayHi()
7.2.5 类变量实例变量以及类方法和实例方法
<code>__author__ = 'vincentc' class Robot: """This is class docString.""" #类变量,只有一份,所有实例都可以访问,一改全改 population = 0 def __init__(self,name): """This is method docString.""" self.name = name Robot.population +=1 def die(self): Robot.population -=1 def sayHi(self): print(self.name) @classmethod #该标注定义类方法 def howMany(cls): print(cls.population) droid1 = Robot("R2-D2") droid1.sayHi() #实例方法的调用方式 Robot.howMany()#类方法的调用方式
7.2.6 私有成员
约定任何名称以一个下划线开头的成员,都为私有成员,但仅仅是约定,不是强制。以两个下划线开头的为强制私有成员,如:__privatevar
7.2.7 类继承
继承的概念和写法大致跟java类似,不同的地方有:
- python继承的父类写在小括号里,且支持多继承,用逗号分开
- 子类在初始化时不会像java那样隐式调用父类的初始化方法,必须要手动显示调用
<code>__author__ = 'vincentc' class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = name self.age = age print('(Initialized SchoolMember: {0})'.format(self.name)) def tell(self): '''Tell my details.''' print('Name:"{0}" Age:"{1}"'.format(self.name, self.age), end=" ") class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print('(Initialized Teacher: {0})'.format(self.name)) def tell(self): SchoolMember.tell(self) print('Salary: "{0:d}"'.format(self.salary)) class Student(SchoolMember): '''Represents a student.''' def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print('(Initialized Student: {0})'.format(self.name)) def tell(self): SchoolMember.tell(self) print('Marks: "{0:d}"'.format(self.marks)) t = Teacher('Mrs. Shrividya', 40, 30000) s = Student('Swaroop', 25, 75) print() # prints a blank line members = [t, s] for member in members: member.tell() # works for both Teachers and Students
八,docString
docString用来描述一个类、方法、模块的用途。
8.1 定义
docString必须放在类、函数(方法)、模块的第一个逻辑行。其余公约如下:
- 第一行首字母大写,并且以点号结尾
- 第二行为空行
- 第三行为具体明细解释
<code>__author__ = 'vincentc' def printMax(x,y): '''Prints the maximum of two numbers. the two values must be integers.''' x = int(x) y = int(y) if x>y: print(x,'is maximum') else: print(y,'is maximum') printMax(3,5) print(printMax.__doc__)
8.2 使用
- 用方法、类、模块名,调用该变量,如:
printMax.__doc__
- 用help方法自动调用,如:
help(printMax)
九,输入输出
9.1 input&print
input可以用来接受用户的输入。print用来打印输出
9.2 读写文件
有多种模式可以打开文件,以读的方式,写的方式等,示例如下:
<code>poem = '''sfsdfsdfsdfsdfsdfsdfs''' f = open('poem.txt', 'w') # open for 'w'riting f.write(poem) # write text to file f.close() # close the file f = open('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default while True: line = f.readline() if len(line) == 0: # Zero length indicates EOF break print(line, end='') f.close() # close the file
9.3 Pickle
将python对象持久化到文件,并可从文件中提取出来,同java的序列化和反序列化类似,示例:
<code>__author__ = 'vincentc' import pickle # the name of the file where we will store the object # shoplistfile = 'shoplist.data' # the list of things to buy # shoplist = ['apple', 'mango', 'carrot'] # Write to the file # f = open(shoplistfile, 'wb') pickle.dump(shoplist, f) # dump the object to a file f.close() del shoplist # destroy the shoplist variable # Read back from the storage # f = open(shoplistfile, 'rb') storedlist = pickle.load(f) # load the object from the file print(storedlist)
9.4 Unicode
如何以utf-8的方式读写文件,示例(注:第一行的注释也是必须的):
<code># encoding=utf-8 f = open("abc.txt", "wt", encoding="utf-8") f.write("Imagine non-English language here") f.close() text = open("abc.txt", encoding="utf-8").read()
十, Exceptions
10.1 处理异常
句型为:
<code>try: .... except [exceptionName]: .... else: ... finally: ...
说明,except语句可以为多个同java类似,exceptionName为可选,如果不写表示拦截所有的Exception,else语句表示没有出现异常时执行的语句。finally表示无论是否有异常都会执行的语句,可以用来关闭文件,或网络链接等资源。当然如果出现异常将不会执行了。示例为:
<code>try: text = input('Enter something --> ') except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation.') else: print('You entered {0}'.format(text))
10.2 抛出异常
可以用raise关键字跑出一个异常对象。异常对象的类型可以是Exception类或任何Exception的子类。定义和跑出异常的示例如下:
<code>class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: text = input('Enter something --> ') if len(text) < 3: raise ShortInputException(len(text), 3) # Other work can continue as usual here except EOFError: print('Why did you do an EOF on me?') except ShortInputException as ex: print('ShortInputException: The input was {0} long, expected at least {1}'\ .format(ex.length, ex.atleast)) else: print('No exception was raised.')
10.3 The with statement
使用finally语句来显示的关闭文件显得不够优雅,更棒的方式是用with。示例:
<code>with open("poem.txt") as f: for line in f: print(line, end='')
这样python自动会去关闭文件,而不需要finally了。关于with语句的解释如下:
What happens behind the scenes is that there is a protocol used by the with statement. It fetches the object returned by the open statement, let’s call it “thefile” in this case. It always calls the thefile.__enter__ function before starting the block of code under it and always calls thefile.__exit__ after finishing the block of code.
So the code that we would have written in a finally block should be taken care of automatically by the __exit__method. This is what helps us to avoid having to use explicit try..finally statements repeatedly.
------from
十一, Standard Library(标准库)
十二, 值得注意的
12.1 Lambda Forms(相当于匿名方法)
lambda接受一个表达式,并将其变成一个函数,表达式的值就是返回值。看明白了吧,这就是java中的匿名类是一个概念。一个按自定义的排序规则排序的例子如下:
<code>points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 } ] points.sort(key=lambda i : i['y']) print(points)
12.2 利用tuble赋值
让一个方法一次返回多个值,或者更方便赋值的方式如下:
<code>Ever wished you could return two different values from a function? You can. All you have to do is use a tuple. >>> def get_error_details(): ... return (2, 'second error details') ... >>> errnum, errstr = get_error_details() >>> errnum 2 >>> errstr 'second error details' Notice that the usage of a, b = <some expression> interprets the result of the expression as a tuple with two values. If you want to interpret the results as (a, <everything else>), then you just need to star it just like you would in function parameters: >>> a, *b = [1, 2, 3, 4] >>> a 1 >>> b [2, 3, 4] This also means the fastest way to swap two variables in Python is: >>> a = 5; b = 8 >>> a, b = b, a >>> a, b (8, 5)
12.3 特殊方法
__init__(self, ...) This method is called just before the newly created object is returned for usage. __del__(self) Called just before the object is destroyed
__str__(self) Called when we use the print function or when str()is used.
__lt__(self, other) Called when the less than operator (<) is used. Similarly, there are special methods for all the operators (+, >, etc.)
__getitem__(self, key) Called when x[key] indexing operation is used.
__len__(self) Called when the built-in len() function is used for the sequence object.
12.4 list的牛逼用法
从已知list来生成一个新的list,新list为原list中大于2的成员乘以2组成。代码如下:
<code>listone = [2, 3, 4] listtwo = [2*i for i in listone if i > 2] print(listtwo)
12.5 参数可变方法
方法可以接受tuble和dictionary做为参数,一个*表示tuble,两个**表示dictionary
There is a special way of receiving parameters to a function as a tuple or a dictionary using the * or ** prefix respectively. This is useful when taking variable number of arguments in the function. >>def powersum(power, *args):
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>powersum(2, 3, 4)
25
>>powersum(2, 10)
100
Because we have a * prefix on the args variable, all extra arguments passed to the function are stored in args as a tuple. If a ** prefix had been used instead,
the extra parameters would be considered to be key/value pairs of a dictionary