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?

  • JackbyDev
    link
    fedilink
    English
    11 month ago

    Classes are like definitions for what objects look like. A lot of times people will use the terms interchangably in non formal settings.

    It so happens that the class they want you to make is like a factory, but not all classes are like that. They can do anything. It’s just a different way to organize your code. Languages like C don’t have classes and you can write Python code without classes. There is a concept called the “factory pattern” (not going to bore you with the details) but suffice to say, it’s a very common thing so your analogy is correct – but as long as you remember not all classes behave like that, just this specific one.