Class in Python

Naming convention in Python

Use PascalCase to name Python Class. The name of the class should have the first letter of every word capitalized.

This is different from the camelCase, where the first word is lower case, and every subsequent word has its first letter capitalized.

There is also the snake_case, where all words are lowercase and they are connected with underscore.

In Python, you will not see much use of camelCase. You will see PascalCase for  Python Class name, and everything else uses snake_case for names.

Constructor

The init function will be called every time you create a new class object. The parameters in the init function must be passed in as parameters when objects are constructed from the class.

The self refers to the actual object being created using the Class. You will use self when defining attributes and methods inside the Class. But you will not use self when using the object that is created outside the Class.

The attributes are the things that an object will have. They are essentially the variables associated with objects.

The methods are the things that an object will do. When a function is attached to an object, it is call the method. An object’s method always have self as the first parameter. This enables the method to be always attached to the object. You can also pass other parameters to the methods.

An example of defining Python Class:

class QuizBrain:
    def __init__(self, questions_list):
        self.question_number = 0
        self.score = 0
        self.questions_list = questions_list

    def next_question(self):
        current_question = self.questions_list[self.question_number]
        self.question_number += 1
        user_answer = input(f"Q.{self.question_number}: {current_question.text} (True/False)?: ")
        self.check_answer(user_answer, current_question.answer)

    def still_have_questions(self):
        return self.question_number < len(self.questions_list)

    def check_answer(self, user_answer, correct_answer):
        if user_answer == correct_answer:
            print("You got it right!")
            self.score += 1
        else:
            print("You got it wrong!")
        print(f"The correct answer is:{correct_answer}")
        print(f"Your current score is: {self.score}/{self.question_number}")
        print("\n")

        if self.question_number == len(self.questions_list):
            print("You have completed the quiz.")
            print(f"Your final score was: {self.score}/{self.question_number}")
Jinyu Du

Jinyu Du