类 和 实例
class Student(object):
def __init__(self, name,score):
super(Student, self).__init__()
self.name = name
self.score = score
def get_grade(self):
if self.score > 60:
return "jige"
else:
return "bujige"
zhangsan = Student("qwerqe",90)
z_grade = zhangsan.get_grade()
print z_grade
异常的捕捉和处理
当 try 语句执行错误的时候会执行except, 如果有 finally语句,则会执行 finally语句。
try: print h except: print "error" finally: print "end"
关于 socket 通信的一个例子
客户端
import socket s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(('47.93.158.182', 9999)) # 接收欢迎消息: print s.recv(1024) for data in ['Tom', 'Tracy', 'Sarah']: # 发送数据: s.send(data) print s.recv(1024) s.send('exit') s.close()
服务端
import socket,threading,time
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('0.0.0.0',9999))
s.listen(5)
print "coming a conn"
def tcplink(sock, addr):
print 'Accept new connection from %s:%s...' % addr
sock.send('Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if data == 'exit' or not data:
break
sock.send('Hello, %s!' % data)
sock.close()
print 'Connection from %s:%s closed.' % addr
while True:
sock, addr = s.accept()
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()
python 执行 shell 命令
import commands
(status,output) = commands.getstatusoutput('service nginx status') print 'status %s' %status print 'output %s' %output
import os
os.system('service nginx status')
import os
out = os.popen('service nginx status')
print out.read()
关于函数的参数
def test(*num): for x in num: print x if __name__ == "__main__": test(4,7,24,2)
输出 4 7 24 2
可以将 list / tuple 作为参数 传入
def test(*num): for x in num: print x a = [3,56,8,23] test(*a)
输出 3 56 8 23
关键字参数
def test(name,age,*num): print "name" + name for x in num: print x test("hello",3,6,3,3)
前面的 name age 是关键字参数 ,后面的 *num 是可选参数
函数的传入
def test(x,y,make): return make(x)+make(y) def make(x): return x+5 print test(2,5,make) 结果是 17
关于 reduce
def add(x,y): return x+y a = [1,4,5,4] b = reduce(add,a) print b #输出14
关于map
def make(x): return x+3 a = [1,4,5,7,8] b = map(make,a) print b
输出的是 4 7 8 10 11
map的高级用法,list 可以是一个函数列表
def add1(x):
return x + 1
def add2(x):
return x + 2
func_list=[add1,add2]
for i in range(4):
print map(lambda x:x(i),func_list)
[1, 2]
[2, 3]
[3, 4]
[4, 5]