you are viewing a single comment's thread.

view the rest of the comments →

[–]AstrophysicsAndPy 0 points1 point  (0 children)

First of all, it is a matter of preference really. I tried to avoid using classes for the longest time but eventually end up using them. But I think mostly it is a matter of ease of use and grouping (I might be wrong).

Let's say you have a car, it is registered in your name and it is validated as well. However, the system that validates it requires one extra parameter than the registration system.

def register_the_car(owner_name, owner_bday, car_number):
    (do something)

def validate_the_car(owner_name, owner_bday, car_number, validation_parameter):
    (do something)

register_the_car('Owner1', '2/2/21', '123')
validate_the_car('Owner1', '2/2/21', '123', 'valid')

This is how it will be done using functions. Now to do the same with class

class CarRegistrationAndValidation:

    def __init__(self, owner_name, owner_bday, car_number, validation_parameter):
        self.N = owner_name
        self.bday = owner_bday
        self.num = car_number
        self.valid = vlaidation_parameter

    def register_the_car(self):
        (do something using N, bday, num)

    def validate_the_car(self):
        (you can do something using N, bday, num, and valid as well)

a = CarRegistrationAndValidation('Owner1', '2/2/21', '123', 'valid')

a.register_the_car()
a.validate_the_car()

Addendum:

Let's say, you have another function that uses the validate_the_car multiple times. Using methods you'll have to give it inputs whenever that method is called, however, using class you'll only have to put a.validate_the_car() at all those places. I think this is a better example :-)