核心编程第十三章(上)

13-3

class MoneyFmt(object):
    def __init__(self, num):
        self.num = num

    def update(self, new_num):
        self.num = new_num

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

    def __repr__(self):
        return '[0:.2f]'.format(self.num)

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

    def dollarize(self, minus=True):
        # list the number
        num = round(self.num, 2)
        num_strlist = str(num).split('.')
        int_strlist = list(num_strlist[0])
        # add ',' into the number
        for i in range(-3, -len(int_strlist), -3):
            int_strlist.insert(i, ',')
        int_str = ''.join(int_strlist)
        # the result
        result = '$' + int_str + '.' + num_strlist[1]
        minuschoice = {True: '-', False: '<->'}
        if num >= 0:
            return result
        else:
            return minuschoice[minus] + result

13-4

import shelve
from time import time


class MyDataBase(object):

    def __init__(self, name, passwd):
        self.name = str(name)
        self.passwd = str(passwd)

        self.db = shelve.open('database')

        self.alogintime = time()

    def newer(self):
        if self.name in self.db:
            return 'name taken, try another.'
        else:
            self.db[self.name] = [self.passwd, 0]

    def older(self):
        print self.db
        passwd = self.db.get(self.name, [None, 0])[0]
        blogintime = self.db.get(self.name, [None, 0])[1]

        if self.alogintime - blogintime <= 14400 and blogintime != 0:
            print 'You already logged in at: <%f>' % blogintime

        if passwd == self.passwd:
            print 'welcome back', self.name
            self.db[self.name][1] = self.alogintime
        else:
            return 'wrong name or password.'

        return True

    def __del__(self):
        self.db.close()
        print 'done'

13-5

class Point(object):

    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return '([0, 1])'.format(self.x, self.y)

    __repr__ = __str__

13-6

from math import sqrt


class MyLine(object):

    def __init__(self, x1, y1, x2, y2, segment=False):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.segment = segment

    def __repr__(self):
        return '(([0], [1]), ([2], [3]))'.format(
            self.x1, self.y1, self.x2, self.y2)

    __str__ = __repr__

    def length(self):
        if self.segment:
            a = (self.y2 - self.y1) ** 2 + (self.x2 - self.x1) ** 2
            return sqrt(2)
        else:
            return 'request a segment, a stright line given.'

    def slope(self):
        if self.x1 == self.x2:
            return None
        else:
            b = self.y2 - self.y1
            a = self.x2 - self.x1
            return float(b) / a

13-7

from time import time, ctime, localtime


class MyTime(object):

    def __init__(self, day=0, month=0, year=0, theformat=None):
        self.theformat = theformat
        self.time = time()
        if day:
            self.day = day
            self.month = month
            self.year = str(year)
        else:
            self.day = localtime(self.time)[2]
            self.month = localtime(self.time)[1]
            self.year = str(localtime(self.time)[0])

    def update(self, day=0, month=0, year=0, defult=False):
        if defult:
            self.day = localtime(self.time)[2]
            self.month = localtime(self.time)[1]
            self.year = str(localtime(self.time)[0])
        else:
            self.day = day
            self.month = month
            self.year = str(year)

    def display(self):
        fmatdict = {'MDY': (self.month, self.day, self.year[2:4]),
                    'MDYY': (self.month, self.day, self.year),
                    'DMY': (self.day, self.month, self.year[2:4]),
                    'DMYY': (self.day, self.month, self.year),
                    'MODYY': (self.month, self.day, self.year)
                    }
        if self.theformat in ('MDY', 'MDYY', 'DMY', 'DMYY'):
            print '{0:02d}/{1:02d}/{2}'.format(*fmatdict[self.theformat])
        elif self.theformat == 'MODYY':
            print '{0:02d} {1:02d}, {2}'.format(*fmatdict['MODYY'])
        elif self.theformat is None:
            print ctime()
        else:
            print 'wrong format.'

13-8

class MyStack(object):

    def __init__(self):
        self.stack = []

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

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

    def popit(self):
        if hasattr(self.stack, pop):
            return self.stack.pop()
        else:
            data = self.stack[-1]
            self.stack = self.stack[0:-1]
            return data

    def pushit(self, value):
        self.stack.append(value)

    def __repr__(self):
        return self.mystack

    def __str__(self):
        return str(self.stack)

13-9

class MyQueue(object):

    def __init__(self):
        self.queue = []

    def enqueue(self, value):
        self.queue.append(value)

    def dequeue(self):
        self.queue.pop(0)

    def __repr__(self):
        return self.mystack

    def __str__(self):
        return str(self.stack)

13-11

class User(object):

    def __init__(self):
        self.mycart = {}
        self.num = 0

    def addcart(self, acart):
        self.num += 1
        self.mycart[self.num] = acart  # an instance of Cart

    def delcart(self, anum):
        del self.mycart[anum]

    def carts(self):
        return self.mycart.viewitems()


class Cart(object):

    def __init__(self):
        self.mygoods = []
        self.item = Item()  # an instance of Item

    def addgoods(self, agood):
        self.mygoods.append(agood)
        self.item.output(agood)

    def rmgoods(self, agood):
        self.mygoods.remove(agood)
        self.item.input(agood)

    def __str__(self):
        return str(self.mygoods)

    __repr__ = __str__


class Item(object):

    def __init__(self):
        self.allgoods = [1, 2, 3, 'a', 'b', 'c']

    def input(self, agood):
        self.allgoods.append(agood)

    def output(self, agood):
        self.allgoods.remove(agood)

    def __str__(self):
        return str(self.allgoods)

    __repr__ = __str__

 

转载于:https://my.oschina.net/u/2519674/blog/683691

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值