Passing Dictionary Values โ€‹โ€‹as Constructor Arguments

I'm new to Python. I need to create a simple student class that includes first name, last name, id, and a dictionary that displays the name of the course in its class.

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

        self.

      

My question is, how do I initialize the dictionary values โ€‹โ€‹inside the constructor?

For example, let's say I would like to add 3 courses to class mappings: "math: 100" "bio: 90" "history: 80"

For example:

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

      

The last 3 values โ€‹โ€‹should go into the dictionary.

Since the number of the key value that can be part of the dictionary can change, what should I write in the signature of the constructor parameter?

I want to send all student values โ€‹โ€‹when the constructor is called ...

+3


source to share


5 answers


If you want to add a Mathias dictionary, it is sufficient to answer the keyword arguments in python.

However, if you want to add object variables from keyword arguments, you need setattr

For example, if you want something like this:

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

      



Then this will do the trick:

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})

      

Note that ** kwargs will only unpack something like a dictionary or a tuple of tuples. If you want to send a list of values โ€‹โ€‹without keys, you must use * args . Check here to find out more.

+4


source


You can try something like:

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

      

And inside your constructor, you can copy these values โ€‹โ€‹into a new dictionary:



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

        self._grades = grades.copy()

      

Note that we are copying the dictionary into the new attribute because we want to avoid the link.

+1


source


Python collects all the keyword arguments for you.

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

        self. _grades = kwargs

      

Here is a great explanation about kwargs in python

+1


source


Why not send the complete class dictionary to your class and store it in a variable. (Also note that there is no semicolon at the end of a line in 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

      

and then when you want to initialize and use evaluations:

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))

      

What prints:

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

      

+1


source


First, be sure to remove the semicolon ;

from your code - it won't compile! Second, I believe you want to do something like:

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()

      

OUTPUT

John
Smith
5
bio 90
math 100
history 80

      

0


source







All Articles