定义一个类:实现功能可以返回随机的10个数字,随机的10个字母, 随机的10个字母和数字的组合;字母和数字的范围可以指定,类似(1~100)(A~z)
#习题2:定义一个类:实现功能可以返回随机的10个数字,随机的10个字母, #随机的10个字母和数字的组合;字母和数字的范围可以指定 class RandomString(): #随机数选择的范围作为参数,如(1~100)字母 ('A'~'z'),大写字母在前 按ascii值排列先后 def __init__(self,start_num=0,end_num=100,start_alpha='A',end_alpha='z'): import string if not isinstance(start_num,int) or not isinstance(end_num,int) or \ not isinstance(start_alpha,str) or not isinstance(end_alpha,str) or \ (start_alpha not in string.ascii_letters or end_alpha not in string.ascii_letters): print('参数类型错误,请重新输入!') return None self.start_num=start_num self.end_num=end_num self.start_alpha=start_alpha self.end_alpha=end_alpha #生成要求数量随机数字,num 随机数的数量 def random_digits(self,num): print('self.start_num,self.end_num:',self.start_num,self.end_num) if not isinstance(num,int): print('数字类型输入错误,请重新输入') return None from random import randint num_list=[] for i in range(num): num_list.append(randint(self.start_num,self.end_num)) return num_list #生成要求数量随机字母,大小写混合 def random_letters(self,num): if not isinstance(num,int): print('数字类型输入错误,请重新输入') return None from random import randint import string all_letters=string.ascii_uppercase+string.ascii_lowercase start_position=all_letters.find(self.start_alpha) end_position=all_letters.find(self.end_alpha) if start_position>end_position: start_position,end_position=end_position,start_position letters_list=[] for i in range(num): letters_list.append(string.ascii_letters[randint(start_position,end_position)]) return letters_list def random_digits_letters(self,num): digits_string=list(range(self.start_num,self.end_num+1)) print('digits_string',digits_string) import string all_letters=string.ascii_uppercase+string.ascii_lowercase print('all_letters',all_letters) print('self.start_alpha',self.start_alpha) print('self.end_alpha',self.end_alpha) start_position=all_letters.find(self.start_alpha) end_position=all_letters.find(self.end_alpha) letters_string=list(all_letters[start_position:end_position+1]) print('letters_string',letters_string) from random import choice all_string=digits_string+letters_string print('all_string',all_string) all_list=[] for i in range(num): all_list.append(choice(all_string)) return all_list randomdigitalpha=RandomString(2,100,'W','e') # print(randomdigitalpha.start_num) print(randomdigitalpha.random_digits(10)) print(randomdigitalpha.random_letters(5)) print(randomdigitalpha.random_digits_letters(15))