How should (or is a clean way) of organising methods in Python?
I always put the __init__
method first, followed by any other __foo__
(What do you call them?) methods. But then it leads into a jumble.
Python follows a depth-first lookup order and hence ends up calling the method from class A. By following the method resolution order, the lookup order as follows. Python follows depth-first order to resolve the methods and attributes. So in the above example, it executes the method in class B.
It doesn't matter in which order variables and functions are defined in Class in Python.
When a python program is executed, python interpreter starts executing code inside it. It also sets few implicit variable values, one of them is __name__ whose value is set as __main__ . For python main function, we have to define a function and then use if __name__ == '__main__' condition to execute this function.
My preference is to place the __init__
method first, then assign the other methods alphabetically afterward.
I like to organize them like this:
First: Constructor (__init__
)
Second: Any other __ methods
Third: Regular methods that roughly can be categorized under "get"
Fourth: Regular methods that roughly can be categorized under "set"
Fifth: Everything else (with any methods that produce anything other than a return value--ie. actually output something or save to a database--being at the very end of this fifth category)
If you follow that pattern consistently, your eye gets used to it and it becomes easy to navigate. Of course, preferences like this vary from person to person.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With