工作以后陆陆续续用过一些Python,今天花时间系统的看了下入门书籍《简明Python教程》(A Byte of Python)。
零、Eclipse安装PyDev
Eclipse --> Help --> Install New Software --> http://pydev.org/updates
一、字符串
1. 字符串可以用三种(其实是四种)符号表示,'...', "...", '''...''', """...""", 除了'''和"""能够轻松处理跨行的字符外,他们没有任何区别;
2. r"..."表示自然字符串,即忽略转义字符‘\’,这在正在表达式中很有用,可以省去大量的转义字符。
3. 字符串是不可修改的。
#!/usr/bin/python # ch04_string_test.py print 'What\'s your name' print "What's your name" print """ "What's your name", I asked. "John." He said. """ print "Hello python.\n" print r"Hello python.\n"
输出:
What's your name What's your name "What's your name", I asked. "John." He said. Hello python. Hello python.\n
二、函数
1. 用"""..."""或'''...'''可以作为函数的注释
2. 默认参数
3. 全局变量 global var
4. 关键参数 fun(val2='b', val1='a', ...)
5. 函数参数是reference还是copy?reference
#!/usr/bin/python # ch07_function_test.py def max_len(str1, str2=""): """ Get the max len of the two string If str2 is empty, use global g_str_list instead. """ if str2=="": global g_str_list g_str_list.append("appended") str2 = g_str_list[0] return max(len(str1), len(str2)) if __name__ == "__main__": print "max_len.__doc_ is", max_len.__doc__ print "max_len('x', 'lxq') is", max_len('x', 'lxq') g_str_list=["l is pig"] print "g_str_list:", g_str_list print "max_len(str1='xiong') is", max_len(str1='xiong') print "g_str_list:", g_str_list
输出:
max_len.__doc_ is Get the max len of the two string If str2 is empty, use global g_str_list instead. max_len('x', 'lxq') is 3 g_str_list: ['l is pig'] max_len(str1='xiong') is 8 g_str_list: ['l is pig', 'appended']
jxion@jxion:~/Learning/python/02_fun$ cat ./fun_ref_or_copy_test.py #!/usr/bin/python def fun(d, l): d['c'] = 3 l.append('c') d = {'a':1, 'b':2} l = ['a', 'b'] print "d:", d print "l:", l fun(d, l) print "d:", d print "l:", l jxion@jxion:~/Learning/python/02_fun$ ./fun_ref_or_copy_test.py d: {'a': 1, 'b': 2} l: ['a', 'b'] d: {'a': 1, 'c': 3, 'b': 2} l: ['a', 'b', 'c'] jxion@jxion:~/Learning/python/02_fun$
三、模块
1. 模块可以理解为C语言里的不同源文件,模块应该与调用者在同一目录,或者环境变量,或者import时使用相对路径。
2. 模块名即为py文件名
3. import module和from module import xxx,yyy...
1 #!/usr/bin/python 2 # my_module.py 3 4 def sayhi(): 5 print "[my_module] This is my first Python module." 6 7 version = "0.1" 8 9 if __name__ == "__main__": 10 print "[my_module] I am running by myself." 11 print "[my_module] version: ", version 12 else: 13 print "[my_module] I am being imported by another module" 14 print "[my_module] version: ", version 15 16 #!/usr/bin/python 17 # import_test.py 18 19 import my_module 20 21 my_module.sayhi() 22 print "my_module version:", my_module.version 23 24 #!/usr/bin/python 25 # fromimport_test.py 26 27 from my_module import sayhi, version 28 29 sayhi() 30 print "my_module version:", version
输出:
jxion@jxion:~/Learning/python/ch08_module$ ./import_test.py [my_module] I am being imported by another module [my_module] version: 0.1 [my_module] This is my first Python module. my_module version: 0.1 jxion@jxion:~/Learning/python/ch08_module$ ./fromimport_test.py [my_module] I am being imported by another module [my_module] version: 0.1 [my_module] This is my first Python module. my_module version: 0.1
四、数据结构
1. 一共有三种内建数据结构:
list(列表): [val1, val2, ...],
tuple(元组): (val1, val2, ...),
dict(字典): {key1:val1, key2:val2, ..}
2. list是可修改的,在Python里无处不在
3. tuple是不可修改的,用的少,常在格式化输出中使用
4. dict的key是不可修改的,val是可修改的;dict的key是没有顺序的。
5. string, list和tuple是sequence(序列), 可以使用’:‘进行一定范围索引
6. 注意list和dict在reference和copy的区别,尤其是list.
jxion@jxion:~/Learning/python/ch09_data_structure$ cat ./list_test.py #!/usr/bin/python a=['0', '12', '4', '3'] print "a:", a print "a[0]:", a[0], "a[-1]:", a[-1] print "" a.append([200, 100]) print "a.append(100):", a print "a[-1][0]:", a[-1][0] print "" a.sort() print "a.sort():", a print "" del a[0] print "del a[0]:", a print "" jxion@jxion:~/Learning/python/ch09_data_structure$ ./list_test.py a: ['0', '12', '4', '3'] a[0]: 0 a[-1]: 3 a.append(100): ['0', '12', '4', '3', [200, 100]] a[-1][0]: 200 a.sort(): [[200, 100], '0', '12', '3', '4'] del a[0]: ['0', '12', '3', '4'] jxion@jxion:~/Learning/python/ch09_data_structure$
jxion@jxion:~/Learning/python/ch09_data_structure$ cat tuple_test.py #!/usr/bin/python age=26 name="jxion" print "%s is %20d yeas old" %(name, age) zoo1 = ('a', 'b') zoo2 = ('a', 'c') zoo_combined = (zoo1, zoo2) print "zoo1:", zoo1 print "zoo2:", zoo2 print "zoo_combined:", zoo_combined jxion@jxion:~/Learning/python/ch09_data_structure$ ./tuple_test.py jxion is 26 yeas old zoo1: ('a', 'b') zoo2: ('a', 'c') zoo_combined: (('a', 'b'), ('a', 'c')) jxion@jxion:~/Learning/python/ch09_data_structure$
jxion@jxion:~/Learning/python/ch09_data_structure$ cat dict_test.py #!/usr/bin/python d = {'a':1, 'c':3, 'b':2} print "d:", d print "d.items():", d.items() print "Traverse d:" for mykey, myvalue in d.items(): print mykey, myvalue print "" # add a key-val d['aa'] = 0 print "d:", d print "Traverse d:" for mykey, myvalue in d.items(): print mykey, myvalue print "" if 'c' in d: print "'c' is in d, the val is", d['c'] jxion@jxion:~/Learning/python/ch09_data_structure$ ./dict_test.py d: {'a': 1, 'c': 3, 'b': 2} d.items(): [('a', 1), ('c', 3), ('b', 2)] Traverse d: a 1 c 3 b 2 d: {'a': 1, 'aa': 0, 'c': 3, 'b': 2} Traverse d: a 1 aa 0 c 3 b 2 'c' is in d, the val is 3 jxion@jxion:~/Learning/python/ch09_data_structure$
jxion@jxion:~/Learning/python/ch09_data_structure$ cat seq_list_tuple_string_test.py #!/usr/bin/python # list my_list = ['apple', 'mango', 'carrot', 'banana'] print 'my_list: ', my_list print 'my_list[0]: ', my_list[0] print 'my_list[-1]: ', my_list[-1] print 'my_list[1:3]:', my_list[1:3] print 'my_list[1:]: ', my_list[2:] print 'my_list[1:-1]', my_list[1:-1] print 'my_list[:] ', my_list[:] print "" # tuple my_tuple = ('apple', 'mango', 'carrot', 'banana') print 'my_tuple: ', my_tuple print 'my_tuple[0]: ', my_tuple[0] print 'my_tuple[-1]: ', my_tuple[-1] print 'my_tuple[1:3]:', my_tuple[1:3] print 'my_tuple[1:]: ', my_tuple[2:] print 'my_tuple[1:-1]', my_tuple[1:-1] print 'my_tuple[:] ', my_tuple[:] print "" #string my_string = 'apple' print 'my_string: ', my_string print 'my_string[0]: ', my_string[0] print 'my_string[-1]: ', my_string[-1] print 'my_string[1:3]:', my_string[1:3] print 'my_string[1:]: ', my_string[2:] print 'my_string[1:-1]', my_string[1:-1] print 'my_string[:] ', my_string[:] print "" jxion@jxion:~/Learning/python/ch09_data_structure$ ./seq_list_tuple_string_test.py my_list: ['apple', 'mango', 'carrot', 'banana'] my_list[0]: apple my_list[-1]: banana my_list[1:3]: ['mango', 'carrot'] my_list[1:]: ['carrot', 'banana'] my_list[1:-1] ['mango', 'carrot'] my_list[:] ['apple', 'mango', 'carrot', 'banana'] my_tuple: ('apple', 'mango', 'carrot', 'banana') my_tuple[0]: apple my_tuple[-1]: banana my_tuple[1:3]: ('mango', 'carrot') my_tuple[1:]: ('carrot', 'banana') my_tuple[1:-1] ('mango', 'carrot') my_tuple[:] ('apple', 'mango', 'carrot', 'banana') my_string: apple my_string[0]: a my_string[-1]: e my_string[1:3]: pp my_string[1:]: ple my_string[1:-1] ppl my_string[:] apple jxion@jxion:~/Learning/python/ch09_data_structure$
jxion@jxion:~/Learning/python/ch09_data_structure$ cat ./reference_copy_test.py #!/usr/bin/python def list_test(): src = ['a', 'b', 'c'] ref = src copy = src[:] del ref[0] del copy[-1] print "src:", src print "ref:", ref print "copy:", copy def dict_test(): src = {'a':1, 'b':2, 'c':3} ref = src #icopy = src[:] del ref['a'] #def copy[-1] print "src:", src print "ref:", ref #print "copy:", copy list_test() print "" dict_test() print "" jxion@jxion:~/Learning/python/ch09_data_structure$ ./reference_copy_test.py src: ['b', 'c'] ref: ['b', 'c'] copy: ['a', 'b'] src: {'c': 3, 'b': 2} ref: {'c': 3, 'b': 2} jxion@jxion:~/Learning/python/ch09_data_structure$
五、面向对象编程
1. 成员变量:static,private&public
2. 成员函数:构造&析构函数,static,private&public
3. 继承
jxion@jxion:~/Learning/python/ch11_OOP$ cat class_test.py #!/usr/bin/python class Person: '''Represents a person.''' num = 0 # static variable # constructor def __init__(self, name, age = 10000): self.name = name # public variable self.__age = age # private variable Person.num += 1 # destructor def __del__(self): Person.num -= 1 print '%s has left. There are still %d people here.' %(self.name, Person.num) # private method def __get_greeting_words(self): return 'Hi, my name is %s. I am %d years old.' % (self.name, self.__age) # public method def sayHi(self): print self.__get_greeting_words() # static method @staticmethod def howMany(): print 'We have %d persons here.' % Person.num if __name__ == "__main__": p1 = Person('p1', 26) p1.sayHi() p1.howMany() # OK Person.howMany() # OK too p2 = Person('p2') p2.sayHi() p2.howMany() jxion@jxion:~/Learning/python/ch11_OOP$ ./class_test.py Hi, my name is p1. I am 26 years old. We have 1 persons here. We have 1 persons here. Hi, my name is p2. I am 10000 years old. We have 2 persons here. p2 has left. There are still 1 people here. p1 has left. There are still 0 people here. jxion@jxion:~/Learning/python/ch11_OOP$
jxion@jxion:~/Learning/python/ch11_OOP$ cat inherit_test.py #!/usr/bin/python class SchoolMember: '''Represents any school member.''' def __init__(self,name,age): self.name=name self.age=age def tell(self): print 'Name:"%s" Age:"%s"' %(self.name,self.age), class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self,name,age,salary): SchoolMember.__init__(self,name,age) self.salary=salary def tell(self): SchoolMember.tell(self) print 'Salary: "%d"' %self.salary class Student(SchoolMember): '''Represents a student.''' def __init__(self,name,age,marks): SchoolMember.__init__(self,name,age) self.marks=marks def tell(self): SchoolMember.tell(self) print 'Marks: "%d"' %self.marks t=Teacher('Mrs. Shrividya',40,30000) s=Student('Swaroop',22,75) members=[t,s] for member in members: member.tell() # works for both Teachers and Students jxion@jxion:~/Learning/python/ch11_OOP$ ./inherit_test.py Name:"Mrs. Shrividya" Age:"40" Salary: "30000" Name:"Swaroop" Age:"22" Marks: "75" jxion@jxion:~/Learning/python/ch11_OOP$
六、异常
TBD。这部分平时关注的不多,也就没什么体会了。
七、其他
1. 列表综合list comprehension
2. lambda表示式:匿名函数,返回值为一个函数
jxion@jxion:~/Learning/python$ cat ch15_list_comprehension_test.py #!/usr/bin/python src_l = [2, 3, 4] des_l = [2*elem for elem in src_l if elem > 2] print "src_l:", src_l print "des_l:", des_l jxion@jxion:~/Learning/python$ ./ch15_list_comprehension_test.py src_l: [2, 3, 4] des_l: [6, 8] jxion@jxion:~/Learning/python$
jxion@jxion:~/Learning/python$ cat ./ch15_lambda_test.py #!/usr/bin/python # lambda statement returns a function name. # before ':' is: arguments list of the function # after ':' is: return value of the function lmd = lambda x, y : x**y print "lmd(3, 4):", lmd(3, 4) print "pow(3, 4):", pow(3, 4) jxion@jxion:~/Learning/python$ ./ch15_lambda_test.py lmd(3, 4): 81 pow(3, 4): 81 jxion@jxion:~/Learning/python$