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

2024-03-28 16:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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个值应该放入字典中。

由于可以作为字典一部分的键值的数目可能不同,我应该在构造函数参数签名中写入什么?

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


Tags: selfiddictionary字典initdeffirstname名字
3条回答

为什么不把完整的成绩字典发送到你的班级,并将其存储在一个变量中。 (请注意,在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

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

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

        self. _grades = kwargs

Here is an excellent explanation about kwargs in python

如果您想添加字典,Mathias的答案就足够用python中的key word arguments了。

但是,如果希望从关键字参数中添加对象变量,则需要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。查看here了解更多信息。

相关问题 更多 >