Python 语法运用

1.
u=[“a”,”b”,”c”]
l = [“name=%s” % user for user in u ]

结果: [“name=a”, “name=b”,”name=c”]

l ={“a”:1,”b”:2,”c”:3}
[k for k,v in l.items()]
结果: [“a”,”b”,”c”]

l ={“a”:1,”b”:2,”c”:3}
[“%s=%s” % (k,v) for k,v in l.items()]
[“a=1″,”b=2″,”c=3”]

2.lambda
lambda 是预代理,代替要生成方法的指针,我这样理解的

d.addCallback(lambda m: “status of %s : %s” % (msg,m))
d.addCallback(lambda m: self.msg(user,m))

3.文件的操作
这是方指的是txt文件操作
# 注意路径只能是 / 的方式处理, 打开的模式,你可以采用 help(file)的方式来查.
f = file(“c:/tmp/abc.txt”,”r”)
for line in f:
user,status = line.split(“:”,1)
user = user.strip()
status = status.strip()
print “%s=%s” % (user,status)

其中 line.split(“:”,1) 是折分串,以 : 区分

f.read()返回字符串内容

4.类的属性
注意类的属性与类的实例属性
class counter:
count = 0
myc = 0
def __init__(self):
self.__class__.count +=1
self.myc +=1

c=counter()
c.count
1
c.myc
1
b=counter()
b.count
2
b.myc
1

可以count是每建一个实例就增加.是类的属性

python的dict,set,list,tuple应用

字典(dict)
dict 用 {} 包围
dict.keys(),dict.values(),dict.items()
hash(obj)返回obj的哈希值,如果返回表示可以作为dict的key
del 或 dict.pop可以删除一个item,clear清除所有的内容
sorted(dict)可以吧dict排序
dict.get()可以查找没存在的key,dict.[]不可以
dict.setdefault() 检查字典中是否含有某键。 如果字典中这个键存在,你可以取到它的值。 如果所找的键在字典中不存在,你可以给这个键赋默认值并返回此值。
{}.fromkeys()创建一个dict,例如: {}.fromkeys((‘love’, ‘honor’), True) =>{‘love’: True, ‘honor’: True}
不允许一个键对应多个值
键值必须是哈希的,用hash()测试
一个对象,如果实现_hash()_方法可以作为键值使用
集合(set)
集合是一个数学概念,用set()创建
set.add(),set.update.set.remove,添加更新删除,-= 可以做set减法
set.discard 和 set.remove不同在于如果删除的元素不在集合内,discard不报错,remove 报错
< <= 表示 子集,> >=表示超集
| 表示联合 & 表示交集 – 表示差集 ^ 差分集里啊
列表(list)
列表是序列对象,可包含任意的Python数据信息,如字符串、数字、列表、元组等。列表的数据是可变的,我们可通过对象方法对列表中的数据进行增加、修改、删除等操作。可以通过list(seq)函数把一个序列类型转换成一个列表。
append(x) 在列表尾部追加单个对象x。使用多个参数会引起异常。
count(x) 返回对象x在列表中出现的次数。
extend(L) 将列表L中的表项添加到列表中。返回None。
Index(x) 返回列表中匹配对象x的第一个列表项的索引。无匹配元素时产生异常。
insert(i,x) 在索引为i的元素前插入对象x。如list.insert(0,x)在第一项前插入对象。返回None。
pop(x) 删除列表中索引为x的表项,并返回该表项的值。若未指定索引,pop返回列表最后一项。
remove(x) 删除列表中匹配对象x的第一个元素。匹配元素时产生异常。返回None。
reverse() 颠倒列表元素的顺序。
sort() 对列表排序,返回none。bisect模块可用于排序列表项的添加和删除。
元组(tuple)
tuple=(1,),这是单个元素的元组表示,需加额外的逗号。
tuple=1,2,3,4,这也可以是一个元组,在不使用圆括号而不会导致混淆时,Python允许不使用圆括号的元组。
和列表一样,可对元组进行索引、分片、连接和重复。也可用len()求元组长度。
元组的索引用tuple[i]的形式,而不是tuple(i)。
和列表类似,使用tuple(seq)可把其它序列类型转换成元组。

Deferred Object In Twisted

Twisted uses the Deferred object to manage the callback sequence. The client application attaches a series of functions to the deferred to be called in order when the results of the asychronous request are available(this series of functions is known as a series of callbacks, or a callback chain), together with a series of functions to be called if there is an error in the asychronous request(known as a series of errbacks or an errback chain). The asychronous library code calls the first callback when the result is available, or the first errback when an error occurs, and the Deferred object then hands the results of each callback or errback function to the next function in the chain.

The Problem that Deferreds Solve

It is the second class of concurrency problem – non-computationally intensive tasks that involve an appreciable delay – that Deferreds are designed to help solve. Functions that wait on hard drive access, database access, and network access all fall into this class, although the time delay varies.

Deferreds are designed to enable Twisted programs to wait for data without hanging until that data arrives. They do this by giving a simple management interface for callbacks to libraries and applications. Libraries know that they always make their results available by calling Deferred.callback and error by calling Deferred.errback. Applications set up result handlers by attaching callbacks and errbacks to deferreds in the order they want them called.

The basic idea behind Deferreds, and other solutions to this problem, is to keep the CPU as active as possible. If one task is waiting on data, rather than have the CPU(and the program!) idle waiting for that data(a process normally called “blocking”), the program performs other operations in the meantime, and waits for some singnal that data is ready to be processed before returning to that process.

In Twisted, a function signals to the calling function that it is waiting by returning a Deferred. When the data is available, the program activeates the callbacks on that Deferred to process the data.

Deferreds – a signal that data is yet to come

In our email sending example above, a parent functions calls a function to connect to the remote server. Asynchrony requires that this connection function return without waiting for the result so that the parent function can do other things. So how does the parent function or its controlling program know that the connection doesn’t exist yet, and how does it use the connection once it does exist?

Twisted has an object that signals this situation. When the connection function returns, it signals that the operation is imcomplete by returning a twisted.internet.defer.Deferred object.

The Deferred has two purposes. The first is that it says “I am a signal that the result of whatever you wanted me to do is still pending.”. The second is that you can ask the Deferred to run things when the data does arrive.

Callbacks

The way you tell a Deferred what to do with the data once it arrives is by adding a callback – asking the Deferred to call a function once the data arrives.

One Twisted library function that returns a Deferred is twisted.web.client.getPage. In this example, we call getPage, which returns a Deferred, and we attach a callback to handle the contents of the page once the data is available:

Python代码

from twisted.web.client import getPage   
from twisted.internet import reactor   
  
def printContents(contents):   
    '''''  
    This is the 'callback' function, added to the Deferred and called by it when the promised data is available  
    '''  
  
    print "The Deferred has called printContents with the following contents:"  
    print contents    
  
    #Stop the Twisted event handling system -- this is usually handled   
    #in higher lever ways   
  
    reactor.stop()    
  
   #call getPage, which returns immediately with a Deferred, promissing to   
   #pass the page contents onto our callbacks when the contents are available   
  
deferred = getPage('http://www.google.com')   
  
#added a callback to the deferred -- request that it run printContents when   
#the page content has been downloaded   
  
deferred.addCallback(printContents)   
  
#Begin the Twisted event handling system to manage the process -- again   
# this isn't the usual way to do this   
  
reactor.run()  

from twisted.web.client import getPage
from twisted.internet import reactor

def printContents(contents):
    '''
    This is the 'callback' function, added to the Deferred and called by it when the promised data is available
    '''

    print "The Deferred has called printContents with the following contents:"
    print contents 

    #Stop the Twisted event handling system -- this is usually handled
    #in higher lever ways

    reactor.stop() 

   #call getPage, which returns immediately with a Deferred, promissing to
   #pass the page contents onto our callbacks when the contents are available

deferred = getPage('http://www.google.com')

#added a callback to the deferred -- request that it run printContents when
#the page content has been downloaded

deferred.addCallback(printContents)

#Begin the Twisted event handling system to manage the process -- again
# this isn't the usual way to do this

reactor.run()

A very common use of Deferreds is to attach two callbacks. The result of the first callback is passed to the second callback:

Python代码

from twisted.web.client import getPage   
from twisted.internet import reactor   
  
def lowerCaseContents(contents):   
     '''''  
     This is a 'callback' function, added to the Deferred and called by  
     it when the promised data is available. It converts all the data to lower  
     case.  
     '''  
  
     return contents.lower()   
  
def printContents(contents):   
  
    '''''  
    This a 'callback' function, added to the Deferred after lowerCaseContents  
    and called by it with the results of lowerCaseContents  
    '''  
    print contents   
    reactor.stop()   
  
deferred = getPage('http://www.google.com')   
  
#add two callbacks to the deferred -- request that it run lowerCaseContents   
#when the page content has been downloaded, and then run printContents with   
#the result of lowerCaseContents   
  
deferred.addCallback(lowerCaseContents)   
  
deferred.addCallback(printContents)   
  
reactor.run() 
from twisted.web.client import getPage
from twisted.internet import reactor

def lowerCaseContents(contents):
     '''
     This is a 'callback' function, added to the Deferred and called by
     it when the promised data is available. It converts all the data to lower
     case.
     '''

     return contents.lower()

def printContents(contents):

    '''
    This a 'callback' function, added to the Deferred after lowerCaseContents
    and called by it with the results of lowerCaseContents
    '''
    print contents
    reactor.stop()

deferred = getPage('http://www.google.com')

#add two callbacks to the deferred -- request that it run lowerCaseContents
#when the page content has been downloaded, and then run printContents with
#the result of lowerCaseContents

deferred.addCallback(lowerCaseContents)

deferred.addCallback(printContents)

reactor.run()

Error handling: errbacks

Just as a asynchronous function returns before its result is available, it may also return before it is possible to detect errors: failed connections, erroneous data, protocol errors, and so on. Just as you can add callbacks to a Deferred which it calls when the data you are expecting is available, you can add error handlers(errbacks) to a Deferred for it to call when an error occurs and it cannot obtain the data:

Python代码

from twisted.web.client import getPage   
from twisted.internet import reactor   
  
def errorHandler(err):   
    '''''  
    This is an 'errback' function, added to the Deferred which will call it in   
    the event of an error  
     '''  
    #this isn't a very effective handling of the error, we just print it out:   
    
    print "An error has occurred: <%s>" % str(err)   
    #and then we stop the entire process:   
    reactor.stop()   
  
def printContents(contents):   
    '''''  
    This is a 'callback' function, added to the Deferred and called by it which   
    the page content  
    '''  
    print contents   
    reactor.stop()   
  
#we request a page which doesn't exist in order to demonstrate the   
#error chain   
  
deferred = getPage("http://www.google.com/does-not-exits")   
  
#add the callback to the Deferred to handle the page content   
  
deferred.addCallback(printContents)   
  
#add the errback to the Deferred to handle any errors   
  
deferred.addErrback(errorHandler)   
  
reactor.run()  

by blog http://huangro.javaeye.com/blog/365988

Python 类型

1.Dictionry {} 相录于一个 key value的内容

mys={“a”:1,”b”:2,”c”:3}
mys[“a”] = 1
mys.keys()
mys.values()

for k,v in mys.items():
print k,v

2.List 是一个列表 []
mys=[“a”,”b”,1]
mys[0]
mys[1]
mys[-1]

for v in mys:
print v;

3. Tuple 一个不能改变的list ()
mys=(1,2,”a”)
mys[0]
mys[1]

for v in mys:
print v;

这三种类型可以完全结合
mys=[(2,3),(4,5),(“a”,”b”)]
mys={“a”:[2,3,4],”b”:[3,4,5]}
mys[“a”].pop() 可以这样的写。