当前位置: 首页 > 工具软件 > SQ v2.0 > 使用案例 >

Python核心编程v2.0 第13章习题(上)

戴鸿羽
2023-12-01

2.
方法是定义在类中的功能函数,只能被实例调用,在所有的方法声明中都必须有self参数。算一种特殊的函数
函数是可以调用的实体,是对程序逻辑进行结构化或过程化的一种编程方法
3.

# -*- coding: utf-8 -*-
class MoneyFmt(object):
    #这个函数写复杂了,可以参考format()函数,相当于自己实现了一次format函数
    def dollarize(self,index=1):
        money = self.money
        st = str(money)
        li = st.split('.')
        count = len(li[0])/3
        #先将符号去掉并记录
        if li[0][0] == '-':
            if index == 1:
                re = '-'
            else:
                re = '<->'
            li[0]=li[0][1:]
        else:
            re = ''
         #数字位不满时补足便于添加逗号
        if len(li[0])%3 != 0:
            li[0]=li[0].rjust((count+1)*3)


        newli = []
        i = 0
        while i < len(li[0])/3:
            # print li[0][0 + i * 3:3 + i * 3]
            newli.append(li[0][0+i*3:3+i*3])
            i=i+1

        #插入逗号以及添加符号
        st = ','.join(newli).lstrip()
        st = re+'$'+st+'.'+li[1]
        return st
    #在类初始化的时候传入d选项需要的参数便于__str__调用
    def __init__(self,money,index):
        self.money = money
        self.index = index

    def update(self,newmoney):
        self.money = newmoney

    def __nonzero__(self):
        if self.money != 0:
            return True

    def __repr__(self):
        return self.money

    def __str__(self):
        return self.dollarize(self.index)

if __name__ =='__main__':
    mon = MoneyFmt(-1234567.88,0)
    print mon.dollarize()
    print mon

4.

# -*- coding: utf-8 -*-
import time

class userdb(object):
    db = {}
    index = False
    #初始化时加载文件信息
    def __init__(self):
        f = open('ar.txt','r')
        lines = f.readlines()
        f.close()
        for line in lines:
            #split返回的是list
            st1 = line.split(':')
            st2 = st1[1].split(',')
            name = st1[0]
            paswd = int(st2[0])
            time = st2[1].strip()
            li = []
            li.append(paswd)
            li.append(time)
            self.db[name] = li

    #登录
    def login(self,name,paswd):
        if self.db[name][0] == paswd:
            print 'your last time login:',self.db[name][1]
            self.db[name][1] = time.strftime("%Y %m %d %H %M", time.localtime())
            self.index = True
        else:
            print 'login fail'

    #添加
    def adduser(self,newname,newpaswd):
        if self.index == True:
            ti = time.strftime("%Y %m %d %H %M", time.localtime())
            li = []
            li.append(newpaswd)
            li.append(ti)
            self.db[newname] = li
        else:
            print 'you have not login in'

    def __del__(self):
        f = open('ar.txt','w')
        for keys in self.db:
            st = keys+':'+str(self.db[keys][0])+','+self.db[keys][1]
            # print st
            f.write(st)
            f.write('\n')
        f.close()

if __name__ =='__main__':
    user = userdb()
    user.login('Anna',2727)
    user.adduser('Cnna',2828)
    # for i in user.db:
    #     print i,user.db[i]
    del user

5.
没啥方法的一个类,只是写了下默认

# -*- coding: utf-8 -*-
class point(object):
    li = []
    def __init__(self,x=0,y=0):
        self.li.append((x,y))

if __name__ =='__main__':
    pi = point(1,19)
    print pi.li

6.

# -*- coding: utf-8 -*-

from __future__ import division
import math

class point(object):
    li = []
    def __init__(self,point1,point2):
        self.li.append(point1)
        self.li.append(point2)

    def __str__(self):
        ti = (self.li[0],self.li[1])
        return str(ti)

    __repr__ = __str__

    def lenth(self):
        q1= abs(self.li[0][0]-self.li[1][0])
        q2 = abs(self.li[0][1]-self.li[1][1])
        return math.sqrt(q1*q1+q2*q2)

    def slope(self):
        q1 = abs(self.li[0][0] - self.li[1][0])
        q2 = abs(self.li[0][1] - self.li[1][1])
        return q2/q1


if __name__ =='__main__':
    po = point((8,3),(2,5))
    print po
    print po.lenth()
    print po.slope()

7.

# -*- coding: utf-8 -*-
import time

class mytime(object):
    def __init__(self,ti = time.localtime()):
        self.ti = ti

    def update(self,ti = time.localtime()):
        self.ti = ti

    def display(self,str=''):
        if str == 'MDY':
            return time.strftime('%m/%d/%y',self.ti)
        elif str == 'MDYY':
            return time.strftime('%m/%d/%Y',self.ti)
        elif str == 'DMY':
            return time.strftime('%d/%m/%y',self.ti)
        elif str == 'DMYY':
            return time.strftime('%d/%m/%Y',self.ti)
        elif str == 'MODYY':
            return time.strftime('Mon %d,%Y',self.ti)
        else:
            sec = time.mktime(self.ti)
            return time.ctime(sec)
if __name__ =='__main__':
    # time.strftime("%Y %m %d %H %M", time.localtime())
    myti = mytime()
    print myti.display('MDY')
    print myti.display('DMYY')
    print myti.display('MODYY')
    myti.update()
    print myti.display()

8.

# -*- coding: utf-8 -*-
class Stack(object):
    def __init__(self):
        self.stack = []

    def push(self,num):
        self.stack.append(num)
        print self.stack

    def isempty(self):
        if len(self.stack) == 0:
            return 1
        else:
            0

    def pop(self):
        if self.isempty() != 1:
            if hasattr(self.stack,'pop'):
                print 'has this attr'
                self.stack.pop()
            else:
                newstack = []
                i = 0
                while i <len(self.stack)-1:
                    newstack.append(self.stack[i])
                    i = i+1
                self.stack = newstack
            print self.stack
        else:
            print 'empty stack can not pop'

    def peek(self):
        return self.stack[len(self.stack)-1]

if __name__ =='__main__':
    stack = Stack()
    stack.push(8)
    stack.push(12)
    stack.pop()
    print stack.peek()

9.

class queue(object):
    def __init__(self):
        self.que = []

    def enqueue(self,num):
        self.que.append(num)
        print self.que

    def dequeue(self):
        #这个地方忘记了要判断队列是否为空了
        newqu = []
        num = self.que[0]
        i = 1
        while i<=len(self.que)-1:
            newqu.append(self.que[i])
            i = i+1
        self.que = newqu
        print self.que
        return num

if __name__ =='__main__':
    que = queue()
    que.enqueue(9)
    que.enqueue(10)
    print que.dequeue()

10.
在stack基础上改的

# -*- coding: utf-8 -*-
class StackandQue(object):
    def __init__(self):
        self.stack = []

    def push(self,num):
        self.stack.append(num)
        print self.stack

    def isempty(self):
        if len(self.stack) == 0:
            return 1
        else:
            0

    def shirf(self):
        if self.isempty() !=1:
            newqu = []
            num = self.stack[0]
            i = 1
            while i<=len(self.stack)-1:
                newqu.append(self.stack[i])
                i = i+1
            self.stack = newqu
            print self.stack
            return num
        else:
            print 'empty '

    def pop(self):
        if self.isempty() != 1:
            if hasattr(self.stack,'pop'):
                print 'has this attr'
                self.stack.pop()
            else:
                newstack = []
                i = 0
                while i <len(self.stack)-1:
                    newstack.append(self.stack[i])
                    i = i+1
                self.stack = newstack
            print self.stack
        else:
            print 'empty stack can not pop'

    def unshif(self,num):
        newstack = []
        newstack.append(num)
        newstack.extend(self.stack)
        self.stack = newstack
        print self.stack

if __name__ =='__main__':
    sq = StackandQue()
    sq.unshif(8)
    sq.unshif(90)
    sq.shirf()

11.

# -*- coding: utf-8 -*-
#item 维护一个 物品仓库 添加进购物车的操作会调用
class Item(object):
    #为了每个实例的更改都能被保存,这个地方不能放在初始化里
    db = {'apple':4,'pear':1,'chocolate':3}

    def check(self,name):
        if self.db[name] != 0:
            return True
        else:
            return False

    def delete(self,name):
        if self.check(name) != 0:
            self.db[name] = self.db[name]-1
            return True
        else:
            print name,'already sold out'
            return False

#car中也有一个字典,用来维护每辆车中的物品
class car(object):
    def __init__(self,carname):
        self.carname = carname
        self.car  = {}

    def addthing(self,name):
        it = Item()
        if it.delete(name) == True:

            if self.car.has_key(name) == True:
                self.car[name] = self.car[name]+1
            else:
                self.car[name] = 1


    def showthings(self):
        for i in self.car:
            print i,self.car[i]

#用户用一个list来存储生成的car对象,之后就用list下标就可以访问到实例
class user(object):
    def __init__(self):
        self.index = 0
        self.carlist = []

    def addcar(self,carname):
        ca = car(carname)
        self.carlist.append(ca)

    def showcar(self):
        for i in self.carlist:
            print i.carname

    def addthing(self,name,carname):
        for i in self.carlist:
            if i.carname == carname:
                i.addthing(name)

    def showthing(self):
        for i in self.carlist:
            print i.carname,'has things:'
            i.showthings()


#调用的逻辑 我做的是用户调用车,车在添加物品是调用物体库
if __name__ =='__main__':
    us = user()
    us.addcar('car1')
    us.addcar('car2')
    us.addthing('pear', 'car1')
    us.addthing('pear', 'car2')
    # us.addthing('chocolate', 'car1')
    us.addthing('pear', 'car2')
    us.showthing()

12.
用户可以发送,接收消息,也可以新建房间,在房间中接收发送消息。
写Room的时候设计的不是很对,其实应该统一用message来进行消息的传递才达到了封装的效果。这个地方单独给room一个数据结构来保存消息了,应该在message里面加字段来实现的。
功能很不完善,大概只做到一个信箱的那种感觉。

# -*- coding: utf-8 -*-
class message(object):
    melib = []

    #新生成一条消息,index = 0表示该消息未读
    def makenew(self,me,nameto,namefrom):
        index = 0
        me1 = me+'   from   '+namefrom
        li = [me1,nameto,index]
        self.melib.append(li)

    #为某个用户查询他接收到的消息
    def checkmessge(self,name):
        for i in self.melib:
            if i[1] == name and i[2] == 0:
                print i[0]
                i[2] = 1

class Room(object):
    #保存参加该房间的用户名称
    namelist = []
    #room message对所有成员可见
    roommessage = []
    def __init__(self,roomname,name1,name2):
        self.roomname = roomname
        self.namelist.append(name1)
        self.namelist.append(name2)

    def addmessage(self,me,name):
        me1 = me + '  from  '+name
        index = 0
        li = [me1,index]
        self.roommessage.append(li)

    def showmessage(self):
        for i in self.roommessage:
            if i[1] == 0:
                print i[0]
                i[1] = 1


class user(object):
    user = []
    roomlist = []

    #用户属性 暂只设置了姓名
    def __init__(self,name):
        self.name = name
        self.user.append(name)

    #用户可以发送信息
    def sendmessage(self,userto):
        if userto in self.user:
            me = raw_input('message:')
            mes = message()
            mes.makenew(me,userto,self.name)
        else:
            print 'no such user'
    #用户可以接收信息
    def accepymessage(self):
        mes = message()
        mes.checkmessge(self.name)

    #创建房间
    def makeroom(self,usname,roomname):
        ro = Room(roomname,usname,self.name)
        self.roomlist.append(ro)

    #向房间中发信息
    def talkroom(self,roomname,mes):
        for i in self.roomlist:
            if i.roomname == roomname:
                i.addmessage(mes,self.name)

    #接收房间中的信息
    def showroommessage(self,roomname):
        for i in self.roomlist:
            if i.roomname == roomname:
                i.showmessage()

if __name__ == '__main__':
    u1 = user('A')
    u2 = user('B')
    u3 = user('C')
    u1.makeroom('B','room1')
    u1.talkroom('room1','hello B')
    u1.makeroom('C','room2')
    u1.talkroom('room2','hello C')
    u2.showroommessage('room1')
    u3.showroommessage('room2')
    u2.talkroom('room1','this is B')
    u1.showroommessage('room1')
    u1.showroommessage('room2')
 类似资料: