Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing dictionary values as constructor's arguments

I am a newbie to Python. I need to create a simple student class which includes first name, last name, id, and a dictionary which maps course name to its grade.

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

        self.

My question is how can I initizalize the dictionary values inside the constructor?

For example, let`s say I would like to add 3 course to grade 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 key-value which can be part of the dictionary can vary, what should I write in the constructor parameter signature?

I want to send all the student values when I call the constructor...

like image 209
qwerty Avatar asked Aug 05 '14 08:08

qwerty


4 Answers

If you are looking to add a dictionary Mathias' answer suffices with the key word arguments in python.

However, if you wish to add object variables from the key word arguments, you require 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 unpack only something like dictionary or tuple of tuples. If you wish to send a list of values without keys, you should use *args. Check here to know more.

like image 96
thiruvenkadam Avatar answered Oct 17 '22 02:10

thiruvenkadam


First, make sure to remove the semicolon ; from your code - it won't compile! Second, I believe you're looking 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
like image 37
Nir Alfasi Avatar answered Sep 20 '22 13:09

Nir Alfasi


Python collects all 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 an excellent explanation about kwargs in python

like image 2
Mathias Avatar answered Oct 17 '22 00:10

Mathias


Why not send the complete grades dictionary to the your class and store it in a variable. (Also please note that in Python there is no semicolon at the end of the line)

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

Which prints:

Marks in bio: 90
Marks in math: 100
Marks in history: 80
like image 2
sk11 Avatar answered Oct 17 '22 02:10

sk11