[Tutor] Constructing a object

eryksun eryksun at gmail.com
Wed Sep 12 07:10:23 CEST 2012

On Tue, Sep 11, 2012 at 10:23 PM, Ashley Fowler
<afowler2 at broncos.uncfsu.edu> wrote:
> How do you construct a object using variables?
> For instance I have to construct a student object, by first prompting the
> user to enter variables for the Student class (their first and last names,
> credits and gpa) then construct a Student object using those variables.

You need to write a function that gets user input and converts it
where appropriate (e.g. int, float).

    def make_student_from_input():

        # input and convert
        first_name = ...
        last_name = ...
        num_credits = ...
        gpa = ...

        return Student(first_name, last_name, num_credits, gpa)

This assumes the Student initializer (__init__) is as follows:

    class Student(object):

        def __init__(self, first_name, last_name, num_credits, gpa):
            # ...

The constructor supplies the 'self' argument in position 0. The rest,
if supplied as "positional" arguments, need to be provided in exactly
the same order as the argument list. The names do not matter. Whatever
argument is in position 1 will be assigned to the local variable
'first_name'. Whatever argument is in position 4 will be assigned to
the local variable 'gpa'.

On the other hand, if you supply each argument name as a "keyword",
you're free to list them in any order. For example:

    first_name, last_name = 'John', 'Doe'
    num_credits, gpa = 60, 3.5

    student = Student(

More information about the Tutor mailing list