面向对象初接触之上手习题
利用类来随机生成一个,随机个数,随机数据段的代码
import random
class RanDomList:
def __init__(self,start:int,stop:int):
self.start = start
self.stop = stop
self._gen = self._generate() #利用next函数调用实例方法实现数据生产
def _generate(self):
while True:
yield [random.randint(self.start,self.stop)for _ in range(self.count)] #利用实例调用的顺序,就可以先定义出次数
def generate(self,count):
self.count = count #在调用实例方法时,自定义生产数据的次数
return next(self._gen)
a = RanDomList(1,100) #可自定义数据字段区间
print(a.generate(20)) #调用类的实例方法同时,将需要的次数也传进去,可自定义数据次数
将上诉代码改为一个生成二元组的代码;
def generate(self,count):
self.count = count #在调用实例方法时,自定义生产数据的次数
return list(zip(next(self._gen),(next(self._gen))
a = RanDomList(1,100)
print(a.generate(20))
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# import random
# class RandomList:
# def __init__(self,patch,start=1,stop=100):
# self._patch = patch
# self._start = start
# self._stop = stop
# self._gen = self._generarte()
# def _generarte(self):
# while True:
# yield [random.randint(self._start,self._stop) for _ in range(self._patch)]
#
# def generate(self):
# return next(self._gen)
#
# @property #使用类装饰器,将数据变得可写
# def patch(self):
# self._patch = path
#
# @patch.setter #若需要修改,直接调用该方法,带上值即可
# def patch(self,value):
# self._patch = value
# #
# # a =RandomList(20)
# # print(a.generate())
# # a.patch = 30
# # print(a.generate())
#
# class Point:
#def __init__(self,x,y):
# self.x = x
# self.y = y
#
# point = [Point(x,y)for x,y in zip(RandomList(3).generate(),RandomList(4).generate())]
#
# for p in point:
# print('{}:{}'.format(p.x,p.y),end=' | ')
#
记录汽车信息:
class Car:
def __init__(self,color:str,price:int,mark:str,speed:int):
self.color = color
self.price = price
self.mark = mark
self.speed = speed
class Carinfo:
def __init__(self):
self.info = []
def addcar(self,car:Car): #这里加入汽车的信息
self.info.append(car)
def getall(self):
return self.info
ac = Carinfo()
ac.addcar(Car('red',88888,'Ford',299)) #输入需要添加汽车的信息
for i in (ac.getall()):
print(i.mark)
天气温度转换:
class Temp:
def __init__(self,t:int,unit='c'):
'''
温度类,提供温度低的转换
:param t: 温度值
:param unit: 单位,k为开式,c为摄氏,f为华氏
'''
self._c = None
self._f = None
self._k = None
#这里只提供了默认摄氏度的转换,若需要其他的类型转换,则调用类的方法即可!
if unit == 'k': #如果传进来的单位为k,则将其转为摄氏度
self._c = self.k2c(t)
self._k = t
elif unit =='f': #如果传进来的单位是f,则将其转为摄氏度
self._c = self.f2c(t)
self._f = t
else:
self._c = t #如果都不是,那肯定传的就是摄氏度,无需转换
@property
def k(self):
if self._k is None:
self._k = self.c2k(self._c)
return self._k
@property
def c(self):
return self._c
@property
def f(self):
if self._f is None:
self._f = self.c2f(self._c)
@classmethod
def c2f(cls,c):
return (c-32)*5/9
@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):
ct=5*(f-32)/9
return ct + 273.15
@classmethod
def k2f(cls,k):
ft=k-273.15
return 9*ft / 5 +32
print(Temp.c2f(400))
购物车定义:
class Color:
RED = 0
BULE =1
GREEN = 2
GOLDEN =3
BLACK = 4
OTHER =1000
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):
self.items.append(item)
def getallitems(self):
return self.items
mycart = Cart()
myphone = Item(mark='huawei',color = Color.GOLDEN,memory='4G')
mycart.additem(myphone) #将所有的数据加入列表中
mycar = Item(mark='Red Flag',color= Color.BLACK,year = 2017)
mycart.additem(mycar)
print(mycart.getallitems())
用类实现打印出一个圆的面积,并将其序列化:
import json
import msgpack
class Shape:
@property
def area(self):
raise NotImplemented('基类未实现')
#~~~~~~~~~~~~~~~~~~~~圆
class Circle (Shape):
def __init__(self,r:int,pi=3.14):
self.pi = pi
self.r = r
@property
def area(self):
return self.pi*(self.r**2)
class SerializableMixin:
def dumps(self,t='json'):
if t =='json':
return json.dumps(self.__dict__)
elif t =='msgpack':
return msgpack.packb(self.__dict__)
else:
raise NotImplemented('未实现的序列化')
class SerializbleCircleMixin(SerializableMixin,Circle): pass
s = SerializbleCircleMixin(5)
print(s.area)
s = s.dumps('msgpack')
print(s)
posted on 2017-11-21 14:37 pythonerLau 阅读(224) 评论(0) 编辑 收藏 举报