PrettyPrincessKitty FS
PrettyPrincessKitty FS

Reputation: 6400

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.

Upvotes: 5

Views: 2484

Answers (4)

Daniel Collins
Daniel Collins

Reputation: 11

I'm not sure if there is an official standard, but I always put the __init__ method first, followed by my own methods, followed by any built ins that I plan on implementing (__str__,__eq__, etc). I try to group methods by similar functionality and order built-ins the same throughout my classes.

Upvotes: 1

Mark Nenadov
Mark Nenadov

Reputation: 6957

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.

Upvotes: 4

Jeffrey Bauer
Jeffrey Bauer

Reputation: 14080

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

Upvotes: 4

Aaron Digulla
Aaron Digulla

Reputation: 328724

I use two strategies:

  • an editor that can fold the code so you don't have to see all of it.
  • I split the big classes into smaller ones where each does only one thing and then build my app from those small blocks.

Upvotes: 1

Related Questions