随机数生成类
import random
class RandomGenerator:
def __init__(self,count=10,minimum=1,maximum=100):
self.count=count
self.min=minimum
self.max=maximum
self.g=self._gen()
def _gen(self):
while True:
yield random.randrange(self.min,self.max)
def gen(self,count=None):
if count is None:
count=self.count
return [next(self.g) for _ in range(count)]
b=RandomGenerator()
print(b.gen(3))
import random
class RandomGenerator:
def __init__(self,minimum=1,maximum=100,count=10):
self.min=minimum
self.max=maximum
self.count=count
def gen(self):
return [random.randint(self.min,self.max) for _ in range(self.count)]
b=RandomGenerator()
print(b.gen())
print(b.gen())
classmethod & staticmethod
import random
class RandomGenerator:
@classmethod
def gen(cls,min=1,max=100,count=10):
return [random.randint(min,max) for _ in range(count)]
@staticmethod
def _gen(min=1,max=100,count=10):
return [random.randrange(min,max+1) for _ in range(count)]
print(RandomGenerator.gen())
print(RandomGenerator.gen())
print(RandomGenerator._gen())
print(RandomGenerator._gen())
print(RandomGenerator()._gen())
print(RandomGenerator()._gen())
添加Point类
import random
class RandomGenerator:
def __init__(self,minimum=1,maximum=100,count=10):
self.min=minimum
self.max=maximum
self.count=count
self.g=self._gen()
def _gen(self):
while True:
yield [random.randint(self.min,self.max) for _ in range(self.count)]
def gen(self,count):
self.count=count # 每次改变对象count属性
return next(self.g)
b=RandomGenerator()
class Point: # class coordinates
def __init__(self,x,y):
self.x=x
self.y=y
def __str__(self):
return '{}=>{}'.format(self.x,self.y)
def __repr__(self):
return '{} : {}'.format(self.x,self.y)
lst=[Point(*v) for v in zip(b.gen(5),b.gen(5))]
print(lst)
for p in lst:
print(p.x,':',p.y)
for p in lst:
print(str(p))

浙公网安备 33010602011771号