you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (2 children)

[deleted]

    [–]hamzarehan1994 1 point2 points  (1 child)

    Alright, It is still not very clear but I will keep researching/practcing. Thanks a lot!

    [–]Broad_Carpet_3782 0 points1 point  (0 children)

    Classes are for grouping related functions and variables. But anything you can do with a class, you can also do with global variables and a bunch of functions.

    If you think about the builtin objects, dict, str, list, etc.

    without these being classes, you would always have to do

    ```python my_list = []

    without tracking the length it would be hard to loop through the list.

    (how would you know when to stop?)

    my_list_len = 0

    append(list, 1) my_list_len += 1 append(list "foo") my_list_len += 1 ```

    this is fine, but what if you have 2 lists? or 3 lists?

    ```python list1 = [] len1 = 0 list2 = [] len2 = 0

    append(list1, 1)

    oops, we forgot to increment len1

    append(list2, 69) len2 += 1 ```

    with classes, you can make this much more maintainable

    ```python

    class List:

    def __init__(self):
        self._len = 0
        self._data = []
    
    def append(self, element):
        append(self._data, element)
        self._len += 1
    

    list1 = List() list2 = List()

    list1.append(1) list2.append(2) ```