python实训

第三天
(一)递归

# 递归
# 斐波那契数 1 1 2 3 5 8
# f(0) = 1,f(1) = 1,f(n) = f(n-1)+f(n-2)
def f(n):
    if n < 2:
        return 1
    else:
        return f(n-1)+f(n-2)
#  将递归改成循环
# x y n
# n=x+y x=y y=n
x=1
y=1
for i in range(10):
    n=x+y
    x=y
    y=n
print(n)

(二)

#信号量,用来保护有限资源的数量
import threading
m = threading.Semaphore(5)
print(m)
m.acquire()
print(m._value)
m.release()
#同步条件
c = threading.Condition()
#主要方法 acquire(),release(),wait(),notify()

(三)类的相关定义和使用

import threading
import time
import random

#包子
class Baozi():
	def __init__(self, count):
		super(Baozi, self).__init__()
		self.count = count
	def add(self,x):
		self.count += x
	def sub(self,x):
		self.count -= x

#以下为生产者和消费者,都继承了Thread类
#生产者
class Producer(threading.Thread):
	def __init__(self, cond, food):
		super(Producer, self).__init__()
		self.food = food #生产的商品为包子
		self.cond = cond #用于控制同步的条件
	def run(self):
		while True:
			time.sleep(5)#每13秒生产一次13个包子
			if food.count<=37:#如果当前数量不足则生产
				cond.acquire()
				food.add(13)
				cond.notifyAll()#通知等待的线程
				cond.release()
				print('生产完毕,数量:%d'%food.count)
			else:#当前数量超过限定值则暂停生产
				print('暂停生产,数量:%d'%food.count)

#消费者
class Consumer(threading.Thread):
	def __init__(self,num,cond,food):
		super(Consumer, self).__init__()
		self.cond = cond #同步条件
		self.food = food #消费的物品
		self.num = num #每次消费数量
	def run(self):
		while True:
			time.sleep(6) #每6秒消费一次
			cond.acquire() #请求锁
			x=random.randrange(4,10)#随机消费4-9个
			if food.count

(四)文件的相关操作

#读文件
#'br'表示一字节为单位进行读取,‘r’以字符为单位进行读取
fn = "/work/javademo/A.class"
f = open(fn,'br')
b = f.read()
f.close()
print(b)
fn = "/work/b1.txt"
f = open(fn,'r')
b = f.read()
f.close()
print(b)
#编码和解码
s = "中国联通"
a = s.encode("utf-8")
b = s.decode("GBK")
print(a)
print(b)
#写文件
fn = "c:\\abc.txt"
f = open(fn,'w')
f.write("你好,python")
f.close()
#追加写入
fn = "c:\\abc.txt"
f = open(fn,'a')
f.write("你好,python")
f.close()

(五)json的相关操作

import json
m = {"name":"Tom张","age":24,"title":("engineer","sportman")}
s = json.dumps(m)#返回一个字符串
print(s)
q = json.loads(s)
print(type(s))
print(type(q))

(六)pickle的相关操作

import pickle
print(prd)
o = pickle.dumps(food)
print(o)
print(type(o))
k = pickle.loads(o)
print(k)
print(type(k))

你可能感兴趣的:(python)