将字典值作为构造函数的参数传递

10 投票
5 回答
32752 浏览
提问于 2025-04-18 16:02

我刚开始学习Python,想创建一个简单的学生类,这个类需要包含学生的名字、姓氏、学号,还有一个字典,用来记录课程名称和对应的成绩。

class Student:
    def __init__(self, firstName, lastName, id, _____ (dictionary values)):
        self._firstName = firstName;
        self._lastName = lastName;
        self._id = id;

        self.

我想问的是,怎么在这个类的构造函数里初始化这个字典的值呢?

比如说,我想添加3门课程的成绩映射: "数学: 100" "生物: 90" "历史: 80"

举个例子:

student1 = Student("Edward", "Gates", "0456789", math: 100, bio: 90, history: 80)

这最后3个值应该放进字典里。

因为字典里的键值对数量可能会变化,我在构造函数的参数里应该写些什么呢?

我希望在调用构造函数的时候,把所有学生的信息都传进去……

5 个回答

1

你可以试试这样的写法:

student = Student("Edward", "Gates", "0456789", {"math": 100, "bio": 90, "history": 80})

然后在你的构造函数里面,你可以把这些值复制到一个新的字典里:

class Student:
    def __init__(self, firstName, lastName, id, grades):
        self._firstName = firstName;
        self._lastName = lastName;
        self._id = id;

        self._grades = grades.copy()

注意,我们把字典复制到一个新的属性里,是因为我们想避免保持对原字典的引用。

1

首先,确保把你的代码中的分号 ; 去掉——否则代码是无法编译的!

其次,我觉得你想要做的事情大概是这样的:

class Student:

    def __init__(self, first_name, last_name, _id, **courses):
        self._first_name = first_name
        self._last_name = last_name
        self._id = _id
        self.courses = courses

    def print_student(self):
        print self._first_name
        print self._last_name
        print self._id
        for key in self.courses:
            print key, self.courses[key]


courses = {'math': 100, 'bio': 90, 'history': 80}    
s = Student("John", "Smith", 5, **courses)
s.print_student()

输出结果

John
Smith
5
bio 90
math 100
history 80
2

Python会自动收集所有的关键字参数。

class Student:
    def __init__(self, firstName, lastName, id, **kwargs):
        self._firstName = firstName;
        self._lastName = lastName;
        self._id = id;

        self. _grades = kwargs

这里有一个关于Python中关键字参数的很棒的解释

2

为什么不把完整的成绩字典发送到你的类里,然后把它存储在一个变量中呢?
(另外请注意,在Python中,行末是没有分号的)

class Student:
    def __init__(self, firstName, lastName, id, grade_dict):
        self._firstName = firstName
        self._lastName = lastName
        self._id = id
        self._grades = grade_dict

    def get_grades(self):
        return self._grades

然后当你想要初始化和使用这些成绩的时候:

student1 = Student("Edward", "Gates", "0456789", {'math': 100, 'bio': 90, 'history': 80})
grades = student1.get_grades()
for key, value in grades.items():
    print 'Marks in {}: {}'.format(key, str(value))

这段代码会输出:

Marks in bio: 90
Marks in math: 100
Marks in history: 80
11

如果你想添加一个字典,Mathias的回答已经足够了,你可以使用Python中的关键字参数

不过,如果你想从关键字参数中添加对象变量,那你就需要用到setattr这个函数。

比如说,如果你想要这样的效果:

student1 = Student("Edward", "Gates", "0456789", {'math': 100, 'bio': 90, 'history': 80})
print student1.math #prints 100
print student1.bio  #prints 90

那么你可以这样做:

class Student(object):
    def __init__(self, first_name, last_name, id, **kwargs):
        self.first_name = first_name
        self.last_name = last_name
        self.id = id
        for key, value in kwargs.iteritems():
            setattr(self, key, value)

student1 = Student("Edward", "Gates", "0456789", {'math': 100, 'bio': 90, 'history': 80})

需要注意的是,**kwargs 只会解包像字典或元组的内容。如果你想发送一组没有键的值,你应该使用*args。想了解更多,可以查看这里

撰写回答