Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I arrange methods in a class in Python?

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.

like image 762
The Communist Duck Avatar asked Mar 18 '11 16:03

The Communist Duck


People also ask

How do you sort class methods in Python?

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.

Does the order of classes matter in Python?

It doesn't matter in which order variables and functions are defined in Class in Python.

Which method executed first 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.


2 Answers

My preference is to place the __init__ method first, then assign the other methods alphabetically afterward.

like image 163
Jeff Bauer Avatar answered Nov 14 '22 21:11

Jeff Bauer


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.

like image 34
Mark Nenadov Avatar answered Nov 14 '22 22:11

Mark Nenadov