python将类作为参数传递

class Student(object):

def __init__(self, name, age, stu_id):
self.name = name
self.age = age
self.stu_id = stu_id

class Class(object):

def __init__(self, Student, class_name):
self.Student = Student
self.class_name = class_name
print(self.Student)
self.stu_list = []
self.stu_dict = {}

def add_student(self, name, age, stu_id):
self.student = Student(name, age, stu_id)
self.stu_dict['name'] = self.student.name
self.stu_dict['age'] = self.student.age
self.stu_dict['stu_id'] = self.student.stu_id
print(self.stu_dict)
self.stu_list.append(self.stu_dict)
print(self.stu_list)

def del_student(self):
del self.student

Python1803 = Class(Student, 1803)
Python1803.add_student('xiaosan', 22, '0016')
Python1803.add_student('xiaodong', 23, '0017')
# Python1803.del_student()
print(Python1803.student)

这一题生成两个对象添加到列表后为什么两个对象完全一样了?自己写的,可能思路不对,求解一下正确的写法

第1个回答  2019-07-18
原因在与空字典和空列表被申明为第二个类的初始化属性,而这个字典的键值对键名又是一样因此两次调用add方法实际上实在对同一个键值对就行操作前面刚给完值后面就会修改他,造成运行以后出现的值都是最后一次调用的,可以空字典的属性声明方法、到add里面去就可以了
第2个回答  2018-05-22
mport sys print sys.argv[1]#保存为main.py#在控制台下输入 python main.py "hello"#就有hello打印出来了 前提是你配置好了环境变量