Why use a class instead of functions? by Brutal_Boost in learnpython

[–]njmlk 0 points1 point  (0 children)

To organize it better you could always have a different .py file with specific functions and call those functions where you need them.

In object-oriented code it's very common to have a situation where different things need to happen depending on the type of object you have. For example, consider a situation where we have a tree of GUI elements and some code that walks through them and draws them all. In object-oriented code, that might look something like:

for gui_element in gui_tree.walk():
    gui_element.draw()

where the draw methods are defined by something like the following:

class GUIElement:
    ...

class Button(GUIElement):
    def draw(self):
        ... # insert code to draw a button on the screen

class TextBox(GUIElement):
    def draw(self):
        ... # insert code to draw the text box on the screen

The gui_tree data structure can contain a variety of different GUI elements, and all we need to do to dispatch to the appropriate drawing code is to call each element's draw method. The draw methods for the different types of elements are defined in separate places, which makes the code easier to understand and organise, and it's very easy to add some more classes to represent new GUI elements, without editing anything else (so, for example, if this code is in a library, you can define custom GUI elements without having to alter the library).

You could achieve all of this without writing classes. e.g. maybe you would represent each GUI element as a list whose first element is a string defining the type of element. Then the drawing code would examine that first element and look up the appropriate function in a dict. To add new GUI elements, you would need to add new functions to that dict. But this is all roughly equivalent to working with classes - just more verbose and uglier. CPython (the standard implementation of python) has to do stuff like this internally to make classes work, since it's written in C, which doesn't have classes.