今天和扬哥讨论如何通过循环定义多变量,从而达到简化定义变量过程的目的,扬哥研究之后让我使用两个函数local()和exec(),local()相当于定义了一个字典并返回了一个局部变量,但是值不能再做改变。而exec()相当于把字符串中的话提取出来,作为一句代码执行。更推荐使用exec()方法,而且该方法的适用性更广泛。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Student(): def __init__(self,name,age,gender,score): self.name=name self.age=age self.gender=gender self.score=score
def info(self): print(f'Name:{self.name},Age:{self.age},gender:{self.gender},score:{self.score}')
for i in range(1,6): lst=(input(f'请输入第{i}个学生的信息:').split('#')) exec(f'stu_{i}=Student(lst[0],lst[1],lst[2],lst[3])')
for i in range(1, 6): locals()[f'stu_{i}'].info()
|