So I have struggled with classes and objects but think I’m starting to get it…? As part of a short online class I made a program that asked a few multiple choice questions and returns a score. To do this there are a few parts.

  1. Define some inputs as lists of strings ((q, a), (q2, a2),…). The lists contain the questions and answers. This will be used as input and allows an easy way to change questions, add them, whatever.

  2. Create a class that takes in the list and creates objects - the objects are a question and it’s answer.

  3. Create a new list that uses that class to store the objects.

  4. Define a function that iterates over the list full of question/answer objects, and then asks the user the questions and tallies the score.

Number 2 is really what I am wondering about, is that generally what a class and object are? I would use an analogy of a factory being a class. It takes in raw materials (or pre-made parts) and builds them into standard objects. Is this a reasonable analogy of what a class is?

  • Scratch@sh.itjust.works
    link
    fedilink
    English
    arrow-up
    4
    ·
    4 months ago

    “Is this a reasonable analogy”

    Kind of. That concept is sometimes referred to as the Factory Pattern. You give it some raw materials and it spits out some products.

    While in this question it does use a class, classes are more basic than that.

    I think of a Class like a blueprint for a car. And each car that is actually built from that blueprint as an Object. The blueprint can have settings, like paint colour, seat fabric and the like.

    For the question in the OP, you can imagine you design a form in Word that you print out. The form has 2 blank fields; Question and Answer. This is a Class. You can call it QuestionClass (terrible name, used for clarity)

    When you print those forms you are creating an Object. Also known as creating an Instance of the Class. Also known as Instantiating.
    Then you can fill in the questions and answers on each sheet/Object.

    You can, however, when designing your Class make it so you MUST supply the question and the answer for this instance when you create it, rather than add them later. You give the class some initial values. You call this an Initialiser.

    Now take a step back. Make a new function that takes in a list of Question-Answer pairs and spits out a bunch of the QuestionClass Objects.

    That’s a big chunk of the work done.