python练习题2---类

1、随机整数生成类

#普通类实现
import random

class RandomGen:
    def __init__(self,start=1,stop=10,count=10):
        self.start=start
        self.stop=stop
        self.count=count

    def generate(self):
        return [random.randint(self.start,self.stop)  for i in range(self.count)]
gen1=RandomGen(1,10)
gen2=RandomGen(20,30)
print(gen1.generate())
print(gen2.generate())
#这种实现适合每一个实例来保存各自的数值范围,互不干扰。


#作为工具类来实现,提供类方法
import  random
class RandomGen:
    @classmethod
    def generate(cls,start=1,stop=100,count=10):
        return  [random.randint(start,stop) for i in range(count)]
print(RandomGen.generate())
print(RandomGen().generate(1,5))
#不需要记录用过的值,只需要调用一次给结果就行
#生成器实现
import  random

class RandomGen:
    def __init__(self,start=1,stop=100,count=10):
        self.start=start
        self.stop=stop
        self.count=count
        self._gen=self._generate()

    def _generate(self):
        while True:
            yield random.randint(self.start,self.stop)
    def generate(self,count=0):   #可以在后期控制产生数字个数
        count=self.count if count <= 0 else count
        return  [next(self._gen) for i in range(count)]
    
print(RandomGen().generate(5))
print(RandomGen().generate())

2、打印坐标。使用上题的类,随机生成20个数字,两两配对形成二维系坐标,把这些坐标组织起来,并打印输出。

import  random

class RandomGen:
    def __init__(self,start=1,stop=100,count=10):
        self.start=start
        self.stop=stop
        self._count=count
        self._gen=self._generate()

    def _generate(self):
        while True:     #一次yield一批
            yield [random.randint(self.start,self.stop) for i in range(self._count)]
    def generate(self):
        return next(self._gen)
    @property
    def count(self):
        return self._count
    @count.setter
    def count(self,count):
        self._count=count

class Point:      #坐标类
    def __init__(self,x,y):
        self.x=x
        self.y=y
r=RandomGen()
points=[Point(x,y) for x,y in zip(r.generate(),r.generate())]
for p in points:
    print("{:2}:{:2}".format(p.x,p.y))

3、车辆信息。记录车的品牌、颜色、价格、速度等特征,并实现车辆管理,能增加车辆、显示全部车辆的信息功能。

class Car:
    def __init__(self,mark,color,price,speed):
        self.mark=mark
        self.color=color
        self.price=price
        self.speed=speed

    def __repr__(self):
        return str(self.__dict__)

class CarInfo:
    def __init__(self):
        self.__info=[]
    def addcar(self,car:Car):
        self.__info.append(car)
    def getall(self):
        return self.__info

ci=CarInfo()
car=Car('audi','red',20,200)
ci.addcar(car)
ci.addcar(Car('redflag','black',30,300))

print(*ci.getall(),sep='\n')
------------------------
{'mark': 'audi', 'color': 'red', 'price': 20, 'speed': 200}
{'mark': 'redflag', 'color': 'black', 'price': 30, 'speed': 300}

4、实现温度的处理

class Tempreature:    #温度类,包含转换方法
    def __init__(self,t,unit='c'):
        self._c=None
        self._f=None
        self._k=None

        #都要先转换到摄氏度,以后访问再计算其他单位的温度
        if unit=='f':
            self._f=t
            self._c=self.f2c(t)
        elif unit=='k':
            self._k=t
            self._k=self.k2c(t)
        else:
            self._c=t
    @property
    def c(self):
        return self._c
    @property
    def f(self):   #华氏温度
        if self._f is None:
            self._f=self.c2f(self._c)
        return self._f
    @property
    def k(self):    #开式温度
        if self._k is None:
            self._k=self.c2k(self._c)
        return self._k

    #温度转换
    @classmethod
    def c2f(cls,c):
        return 9 * c / 5 +32
    @classmethod
    def f2c(cls,f):
        return (f-32) * 5 / 9
    @classmethod
    def c2k(cls,c):
        return  c + 273.15
    @classmethod
    def k2c(cls,k):
        return k - 273.15

    #华氏温度和开式温度如何转换?
    @classmethod
    def f2k(cls,f):
        return cls.c2k(cls.f2c(f))
    @classmethod
    def k2f(cls,k):
        return cls.c2f(cls.k2c(k))

print(Tempreature.c2f(40))
print(Tempreature.f2c(104))
print(Tempreature.c2k(40))
print(Tempreature.k2c(313.15))
print(Tempreature.f2k(104))
print(Tempreature.k2f(313.15))

t=Tempreature(104,'f')
print(t.__dict__)
print(t.c,t.k,t.f)
print(t.__dict__)

5、模拟购物车购物

class Color:
    red=0
    blue=1
    black=2

class Item:
    def __init__(self,**kwargs):
        self.__spec=kwargs
    def __repr__(self):
        return str(sorted(self.__spec.items()))
class Cart:
    def __init__(self):
        self.items=[]
    def additem(self,item:Item):
        self.items.append(item)
    def getallitems(self):
        return self.items

mycart=Cart()
myphone=Item(mark='Huawei',color=Color.black,memory='4G')
mycart.additem(myphone)
mycar=Item(mark='RedFlag',color=Color.blue,year=2018)
mycart.additem(mycar)
print(*mycart.getallitems(),sep='\n')
---------------------
[('color', 2), ('mark', 'Huawei'), ('memory', '4G')]
[('color', 1), ('mark', 'RedFlag'), ('year', 2018)]
#真正的购物车还要添加很多代码,增删查改等。

个人博客---------->     网子世界

 

你可能感兴趣的:(python练习题2---类)