Python作为一门高级语言 拥有简单高效的数据结构 有区别于传统语言C C++ Java 在Python 里编程变得极其简单让人上瘾的切片(slide sequences)表达式会让C程序员感到震撼 让我们花5分钟来熟悉一下如何使用切片进行简单的Python编码 花费宝贵的5分钟 进入Python的世界
可以向这样操作一个数组 Array[index]
$ >>> foo=”hello world”
$ >>> print foo[1]
$ e
也可以这样 Array[ind1 : ind2] 切片操作
$ >>> foo=”hello world”
$ >>> print foo[5:]
$ world
切片复制 seq * expr seq[]重复expr次
$ >>> foo=”hello world!”
$ >>> print foo*3
$ hello world! hello world! hello world!
切片拼装 seq1+seq2
$ >>> foo=”This time I will not repeat”
$ >>> bar=” Hello World”
$ >>> print foo+bar
$'This time I will not repeat Hello World'
Object in array/sequences 切片检索
>>> "Hello " in foo+bar
True
[:] 切片拷贝 使用[:]操作符将获得一个新的内存拷贝
>>> (foo+bar)
'This time I will not repeat Hello World'
>>> (foo+bar)[:]
'This time I will not repeat Hello World'
>>> (foo+bar)[:-3]
'This time I will not repeat Hello Wo'
>>> (foo+bar).split(" ")
['This', 'time', 'I', 'will', 'not', 'repeat', 'Hello', 'World']
值得注意的是 最后一个函数split(“…”)不是一个标准的list对象方法 而是专属于字符串对象的
[::*step]更加灵活的切片操作 step(步长)
>>> foo = "This time I will Not repeat Hello World".split(" ")
>>> foo
['This', 'time', 'I', 'will', 'Not', 'repeat', 'Hello', 'World']
>>> foo[:-2]
['This', 'time', 'I', 'will', 'Not', 'repeat']
>>> foo[::2]
['This', 'I', 'Not', 'Hello']
>>> foo[1::2]
['time', 'will', 'repeat', 'World']
>>> foo[::-1]
['World', 'Hello', 'repeat', 'Not', 'will', 'I', 'time', 'This']
>>> foo[len(foo)-2:]
['Hello', 'World']
>>> s = 'google'
>>> for i in range(0,len(s)+1):
... print s[:i]
...
g
go
goo
goog
>>> for i in range(0,len(s)+1):
... print s[i:]
...
oogle
ogle
gle
le
e
#是否”切”到了你需要的结果?
检查元素是否在一个表达式中 Python采用特别有趣的两个关键字 not in
Example 1 (Primes.py)
01 |
<b> # 计算100以内的所有素数 |
02 |
#!/usr/bin/env python |
03 |
# Primes < 100 |
04 |
def primes(num,d = []): |
05 |
for x in xrange ( 2 ,num): |
06 |
isprime = True |
07 |
for y in d: #[2,math.sqrt(x)+1] is also OK.. |
08 |
if x % y = = 0 : |
09 |
isprime = False |
10 |
break |
11 |
else : |
12 |
continue |
13 |
if isprime : |
14 |
d.append(x) |
15 |
print d |
16 |
primes( 100 )< / b> |
>>> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
编程语言的进化史
-----------脚本语言一般出身贫贱,它们源自批处理语言,最初用来粘合其他程序。今天的动态脚本语言已经自成一统,成为编写互联网应用的流行语言
天下语言 皆效C之形Lisp之神 而Python作为一个继承者 很好的融合了这两大语言的血脉 典型的特征就是 lambda----Lisp语系程序员的最爱 尤其是haskell
因为可以自由地选择面向对象和面向过程 故而将title起名为”二次元世界”
跟C语系的语言(Java/C++/C/Delphi)不同 Python使用缩进来识别代码块 前者花括号{} 读者也许会觉得上面的代码简直是在浪费生命!---同样的逻辑用C写 似乎效率更高 而Python的意义何在?
细心观察 你会发现 上面求素数的代码其实写得相当丑陋 不妨看看下面一段代码:
Example 2 (Primes_lambda.py)
1 |
<p> |
2 |
#计算100内的素数</p> |
3 |
<p><b> print filter ( None , map ( lambda y:y * reduce ( lambda x,y:x * y! = 0 ,< / b>< / p> |
4 |
<b> map ( lambda x,y = y:y % x, range ( 2 , int ( pow (y, 0.5 ) + 1 ))), 1 ), range ( 2 , 100 )))< / b> |
>>> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Oops! %#$($&)#%!…
这是什么狗屎代码?
官方的解释是 : Don’t try this at home kids //只属于程序员的幽默
有人的地方就有江湖 封装性良好的OOP语言是敏捷开发者的最爱 或曰码农的最爱 lambda风格的Python代码自2系以后已经很少有人能玩转了 多为极客所用, 一名极客可以很潇洒地写出楼上那样万人敬仰的代码 同时对于新人,Python的OOP功能也是十分强大的,体现在API上,在$PATH/LIB下有很多内置电池(Build-in battery) python文件 大多是 纯python代码 少量为C 编译过后的内建函数
使用3行代码制作一个简单的日历 在任何时候都是一件令人愉快的事….
Example 3 (cal.py)
1 |
<b> import calendar |
2 |
|
3 |
year = input ( "Type in the year number:" ) |
4 |
5 |
calendar.prcal(year)< / b> |
>>> Type in the year number:2001
>>>
2012
January February March
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 1 2 3 4 5 1 2 3 4
2 3 4 5 6 7 8 6 7 8 9 10 11 12 5 6 7 8 9 10 11
9 10 11 12 13 14 15 13 14 15 16 17 18 19 12 13 14 15 16 17 18
16 17 18 19 20 21 22 20 21 22 23 24 25 26 19 20 21 22 23 24 25
23 24 25 26 27 28 29 27 28 29 26 27 28 29 30 31
30 31
模块一览 help()->modules
使用TCP协议
mysql.connector是在python.org上扒的 作者信息不详 但完美支持UTF8和套接字连接 以及连接池
使用原始套接字登陆数据库只需要更改一个参数
1 |
<i>db = mysql.connector.Connect(user = 'root' ,password = 'sa' ,unix_socket = '/tmp/mysql.sock' )< / i> |
Example (testmysql.py)
01 |
<b>Example (testmysql.py) |
02 |
#!/usr/bin/env python |
03 |
04 |
import mysql.connector |
05 |
if __name__ = = '__main__' : |
06 |
db = mysql.connector.Connect(user = 'root' ,password = 'sa' ) |
07 |
cursor = db.cursor() |
08 |
cursor.execute( "select user,host,password as mima from mysql.user" ) |
09 |
for row in cursor.fetchall() |
10 |
print row |
11 |
12 |
>>> < / b> |
>>>
('root','localhost',*4D0DD263C1DE57138354E81A957460B774C4BC2’)
('', 'localhost', '')
('', '%', '')
('root', '%', '*4D0DD2673C1DE57138354E81A957460B774C4BC2')
Hit any key to close this window...
观察一下 下面的sqlite3代码 几乎不需要作任何更改 同上mysql数据库大同小异
01 |
<b> #!/usr/bin/env python |
02 |
#-*- encoding: utf-8 -*- |
03 |
04 |
__author__ = 'vikid' |
05 |
__version__ = 1.0 |
06 |
07 |
""" |
08 |
Python New Features ----Loging via Yaml or json format |
09 |
as a persistant config storeage solution |
10 |
""" |
11 |
12 |
#just a simple demo via Module/loging and loging.config |
13 |
import logging |
14 |
import logging.config |
15 |
16 |
configdict = { |
17 |
'version' : 1 , # Configuration schema in use; must be 1 for now |
18 |
'formatters' : { |
19 |
'standard' : { |
20 |
'format' : ( '%(asctime)s %(name)-15s ' |
21 |
'%(levelname)-8s %(message)s' )}}, |
22 |
23 |
'handlers' : { 'netlog' : { 'backupCount' : 10 , |
24 |
'class' : 'logging.handlers.RotatingFileHandler' , |
25 |
'filename' : 'network.log' , |
26 |
'formatter' : 'standard' , |
27 |
'level' : 'INFO' , |
28 |
'maxBytes' : 1000000 }, |
29 |
'syslog' : { 'class' : 'logging.handlers.SysLogHandler' , |
30 |
'formatter' : 'standard' , |
31 |
'level' : 'ERROR' }}, |
32 |
33 |
# Specify all the subordinate loggers |
34 |
'loggers' : { |
35 |
'network' : { |
36 |
'handlers' : [ 'netlog' ] |
37 |
} |
38 |
}, |
39 |
# Specify properties of the root logger |
40 |
'root' : { |
41 |
'handlers' : [ 'syslog' ] |
42 |
}, |
43 |
} |
44 |
45 |
# Python 2.7内置电池 log4python 受启发于log4j |
46 |
logging.config.dictConfig(configdict) |
47 |
48 |
# 使用方法 |
49 |
logger = logging.getLogger( '/' ) |
50 |
logger.error( 'Database not found' ) |
51 |
52 |
netlogger = logging.getLogger( 'network' ) |
53 |
for x in xrange ( 10000000 ): |
54 |
netlogger.error( 'Connection failed' )< / b> |
运行截图:
3大数据类型 – 数字 ,表达式 ,对象与类
>>> type(1)
<type 'int'>
>>> type(1L)
<type 'long'>
>>> type(1-2j)
<type 'complex'>
>>> type("世界,你好")
<type 'str'>
>>> type([])
<type 'list'>
>>> type(())
<type 'tuple'>
>>> type({})
<type 'dict'>
Long decimal int complex属于数字类型 字符串 字典元组列表 set属于可迭代类型 即切片 class和instance 属于OOP 类型
Python和Javascript的数据类型是所有编程语言里最为 简单优雅的
Python语言 一个包(文件夹) 或者一个py文件 就是一个模块 以__init__.py为界定符 包中包以此类推 如无包中包modules.xx 直接指向对象 不同于Java 一切引用都是指针 函数也是指针 可以自由传递而不需要创建新的对象(自动创建)
下面一行代码就可以反射出任意的python对象的方法清单
Example-5 reflection.py
01 |
<b> #!/usr/bin/env python |
02 |
def info_Py( cls ,spacing = 10 , format = false): |
03 |
''' |
04 |
/---------------------------------------------------------------------} |
05 |
| --List all methods in class file or function names in module... --| |
06 |
| --module name,class name imported and string is allowed parameters--| |
07 |
\---------------------------------------------------------------------/ |
08 |
''' |
09 |
return "\n" .join( |
10 |
[ |
11 |
"""[%s] Docs:=> [%s] |
12 |
%s """ % (x.center(spacing) , getattr ( cls ,x).__doc__.center(spacing * 3 )," ###"*20) |
13 |
for x in [y for y in dir ( cls )] if "__" not in x and callable ( getattr ( cls ,x)) |
14 |
] |
15 |
) |
16 |
17 |
#-----------------------测试主函数----------------------- |
18 |
if __name__ = = "__main__" : |
19 |
print info_Py([])< / b> |
[ append , count , extend , index , insert , pop , remove , reverse , sort ]
可以看到 另外三种切片类型的方法都很少 除字典{}以外 都不超过10个内置方法
元组
[ count , index ]
字典
[ … ]
字符串
[ … ]
and elif if print
as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass
help>
同Java 每一次对字符串的修改操作 都会作用于一个新的变量空间 因为一切都是对象
Python内建方法build-in Id()等同于Java语言中的hashcode()
hashcode现实意义在于: 从技术上讲 90年代后期兴起的编程语言多采用动态内存分配 dynamic memory control 程序员不需要手动处理底层指针 从而使得编程变得简单 同时降低编程带来的负面作用 让程序员编写更加”安全”的程序 ---所谓的”安全” 更多是企业处于利益上的考虑 通过更改编程语言的工作模式来控制程序员的权利
在这种”黑箱”模式中 程序员无法控制指针 但编译器必须控制底层数据所以需要一个”伪指针地址” 也就是后来Java的hashcode Python的id()
可以看到 字符串是”不可变的” 本质上属于动态数组 所以两次操作以后的hashcode都不一样 这一点同Java .字符串”hello world”