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

10

我是Python新手。我需要创建一个简单的学生类,其中包括名字、姓氏、ID以及一个将课程名称映射到其成绩的字典。

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

        self.

我的问题是如何在构造函数中初始化字典值?

例如,假设我想要添加3个课程到成绩的映射关系: "math: 100" "bio: 90" "history: 80"

例如:

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

最后的3个值应该放入字典中。

由于可以作为字典一部分的键-值对数量可能会变化,所以我在构造函数参数签名中应该写什么?

我想在调用构造函数时发送所有学生值...


1
你可以只使用一个字典变量。 - sapi
5个回答

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。请查看 这里 以了解更多信息。

当我尝试相同的命令时,我会得到这个错误:"TypeError: Student.init()需要4个位置参数,但提供了5个"。为什么? - Nilay İnel

2

Python为您收集所有的关键字参数。

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

        self. _grades = kwargs

这里有一个关于Python中kwargs的优秀解释


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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接