Welcome To PyCrust 0.7.2 - The Flakiest Python Shell
Sponsored by Orbtech - Your source for Python programming expertise.
Python 2.2.1 (#1, Aug 27 2002, 10:22:32)
[GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)] on linux-i386
Type "copyright", "credits" or "license" for more information.
>>> import cPickle as pickle
>>> t1 = ('this is a string', 42, [1, 2, 3], None)
>>> t1
('this is a string', 42, [1, 2, 3], None)
>>> p1 = pickle.dumps(t1)
>>> p1
"(S'this is a string'\nI42\n(lp1\nI1\naI2\naI3\naNtp2\n."
>>> print p1
(S'this is a string'
I42
(lp1
I1
aI2
aI3
aNtp2
.
>>> t2 = pickle.loads(p1)
>>> t2
('this is a string', 42, [1, 2, 3], None)
>>> p2 = pickle.dumps(t1, True)
>>> p2
'(U\x10this is a stringK*]q\x01(K\x01K\x02K\x03eNtq\x02.'
>>> t3 = pickle.loads(p2)
>>> t3
('this is a string', 42, [1, 2, 3], None)
>>> j = [1, 2, 3]
>>> k = j
>>> k is j
1
>>> x = pickle.dumps(k)
>>> y = pickle.loads(x)
>>> y
[1, 2, 3]
>>> y == k
1
>>> y is k
0
>>> y is j
0
>>> k is j
1
class Foo(object):
def __init__(self, value):
self.value = value
现在可以 pickle Foo 实例,并看一下它的表示:
清单 12. pickle Foo 实例
>>> import cPickle as pickle
>>> from Orbtech.examples.persist import Foo
>>> foo = Foo('What is a Foo?')
>>> p = pickle.dumps(foo)
>>> print p
ccopy_reg
_reconstructor
p1
(cOrbtech.examples.persist
Foo
p2
c__builtin__
object
p3
NtRp4
(dp5
S'value'
p6
S'What is a Foo?'
sb.
>>>
>>> import cPickle as pickle
>>> f = file('temp.pkl', 'r')
>>> foo = pickle.load(f)
Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named persist
class Foo(object):
def __init__(self, value, filename):
self.value = value
self.logfile = file(filename, 'w')
def __getstate__(self):
"""Return state values to be pickled."""
f = self.logfile
return (self.value, f.name, f.tell())
def __setstate__(self, state):
"""Restore state from the unpickled state values."""
self.value, name, position = state
f = file(name, 'w')
f.seek(position)
self.logfile = f
假定已经创建并 pickle 了 Person 的实例,现在我们决定真的只想存储一个名称属性,而不是分别存储姓和名。这里有一种方式可以更改类的定义,它将先前经过 pickle 的实例迁移到新的定义:
清单 18. 新的类定义
class Person(object):
def __init__(self, fullname):
self.fullname = fullname
def __setstate__(self, state):
if 'fullname' not in state:
first = ''
last = ''
if 'firstname' in state:
first = state['firstname']
del state['firstname']
if 'lastname' in state:
last = state['lastname']
del state['lastname']
self.fullname = " ".join([first, last]).strip()
self.__dict__.update(state)
# encoding:utf-8
#
#author:0x55aa
#team:Pax.Mac Team
#time:2012.08.17
#
import urllib2,urllib,time
import threading
from Queue import Queue
from BeautifulSoup import BeautifulSoup
#提交的地址
URL = ""
#密码列表example:['0x55aa','1','b']
passwdlist = ['0x55aa','123','a']
#生产密码长度
passwdlen = 3
#密码生成完毕
passwd_done = False
#队列为空啦,这个可以用Queue.empty()
#post_done = False
#锁,用于输出
lock = threading.Lock()
#tag标识是否找到密码退出
tag = False
#密码
def perm(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[:i] + items[i+1:]
for p in perm(rest, n-1):
yield v + p
def sqlPost(password):
"""提交奥"""
#提交字段的设置在这里。。
post_params = [
('UserName', 'root'),
('Password', password),
]
data = urllib.urlencode(post_params)
req = urllib2.Request(URL)
r = urllib2.urlopen(req,data)
#这里加入返回数据的判断
"""
soup = BeautifulSoup(r.read())
list1 = soup.find('value')
"""
return list1
class PasswordProduce(threading.Thread):
"""生成密码"""
def __init__(self,queue,first,items,n):
threading.Thread.__init__(self)
self.passwd = queue
self.first = first
self.items = items
self.n = n
def run(self):
#生成密码
r = perm(self.items,self.n)
for i in r:
p = self.first + ''.join(i)
#密码插入队列
self.passwd.put(p)
"""
if lock.acquire():
print p
lock.release()
"""
class Sqlpost(threading.Thread):
"""提交"""
def __init__(self,queue):
threading.Thread.__init__(self)
self.passwd = queue
def run(self):
#post提交
global passwd_done
while not (passwd_done and self.passwd.empty()):
"""
if lock.acquire():
print self.getName(),passwd_done , self.passwd.empty()
lock.release()
"""
#取得密码
if not self.passwd.empty():
p = self.passwd.get()
else:
time.sleep(2)
continue
"""
if lock.acquire():
print p
lock.release()
"""
#提交
r = sqlPost(p)
#打印返回信息
global tag
if r:
tag = True
if lock.acquire():
print "password:",p,">>the result:",r
#print r
lock.release()
if tag:
break
def main():
queue = Queue()
#密码线程
passwdthread = []
#post
postthread = []
#线程数
s = len(passwdlist)
for i in range(s):
first = passwdlist[i]
lastlist = passwdlist[:i]+passwdlist[i+1:]
thelen = passwdlen - 1
pp = PasswordProduce(queue,first,lastlist,thelen)
sp = Sqlpost(queue)
passwdthread.append(pp)
postthread.append(sp)
pp.start()
sp.start()
for t in passwdthread:
t.join()
#设置,密码生产完毕
global passwd_done
passwd_done = True
print "\npassword is produced done\n"
for t in postthread:
t.join()
print "\nAll done!\n"
if __name__ == '__main__':
main()
function getCookie(sName){
var aCookie=document.cookie.split("; ");
for(var i=0;i<aCookie.length;i++){var aCrumb=aCookie[i].split("=");if(sName==aCrumb[0])
return(aCrumb[1]);}return null;}
package main
import "fmt"
type S struct {
i int
}
func (p *S) Get() int {
return p.i
}
func (p *S) Put(v int){
p.i = v
}
type I interface{
Get() int
Put(int)
}
func f(p I){
fmt.Println(p.Get())
p.Put(1)
}
func main(){
var s S
f(&s)
fmt.Println(s.Get())
}
结果:
D:\code>go run 7.go
24
0
12
r1: 24
12
314.1592653589793
12.566370614359172
代码中有两个同名方法area,他们前面括号里是ReceiverType,称作receiver。
拥有不同receiver的方法是不同的,即使他们有相同的名字。
内建类型不能定义方法,但是可以定义一个有方法的这种类型。如:
type ages int
setarea()修改了字段rarea的值,比较setarea()和setarea2(),会发现如果不使用指针,赋值操作是给了一个复制版的r,
并不是原来的值。
匿名字段代码:
package main
import "fmt"
type Human struct{
name string
age int
phone string
}
type Employee struct{
Human//Human类型的匿名字段
speciality string
phone string
}
func main(){
Bob := Employee{Human{"bob",34,"777777-3"},"designer","33-22"}
fmt.Println(Bob.name)
fmt.Println(Bob.phone)
fmt.Println(Bob.Human.phone)
fmt.Println(Bob.Human.name)
}
运行结果:
D:\code>go run 8.go
bob
33-22
777777-3
bob
从程序中,当有字段冲突时,我们必须写全字段名称;当没有冲突时,两种方式都可以。