5

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.

1
  • 1
    Read other people's code, please. Pick a random open source Python project. Read their code. Special method names (__ names) are what you're looking for. Before asking, you should bookmark the Python language reference and check there first. Commented Mar 18, 2011 at 17:00

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

1

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.

5 Comments

I can see what you mean, but what I meant more was that even if I fold up blocks, I spend a while scrolling back and forth because I miss the method I'm looking for, it being in some random place.
Get an editor where you can quickly find a method by typing a few characters of the name. I use Eclipse with PyDev and the Outline view has a search option. Or I can use Ctrl+J, Ctrl+K or F3.
@The Communist Duck: This is where a good editor comes in handy. Use one that will let you jump to the definition of a function/method and back without a lot of fuss. The vast majority of programming editors should be able to handle it.
I use PyDev, but I never really fiddled with search or anything. :P
Bad for you :-) Eclipse offers at least ten ways to find something in the source and you should know at least four.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.