2

What is better? Call the method first and define it later:

class Class(object):
    def foo(self):
        # do something
        self.bar()

    def bar(self):
        # do something else

or define the method first and call it later:

class Class(object):
    def bar(self):
        # do something else

    def foo(self):
        # do something
        self.bar()

I know the result will be equal. But which version is easier to read?

lampslave
  • 1,431
  • 1
  • 15
  • 20
  • 2
    It doesn't matter; `bar` isn't called until after the class has been defined. Order your methods however makes most sense to you. For example, I generally put `__init__` at the top of the class, even if it calls other methods that appear later. – jonrsharpe May 30 '15 at 09:01
  • 2
    preferable is *Define the method first and call it later* – ZdaR May 30 '15 at 09:01
  • 1
    @ZdaR [Clean Code](http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) suggests writing code to read from top to bottom, so higher functions delegate to other functions which are defined further down. – Peter Wood May 30 '15 at 09:39
  • 1
    Related: http://stackoverflow.com/q/10289461/3001761 – jonrsharpe May 30 '15 at 09:45

2 Answers2

2

You won't always be able to choose anyway (because of mutual recursion). You should put the methods in the order that makes the most sense for the class definition, i.e., disregarding the code within them.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
1

The tradition suggests to put the constructor at the first position. Then it's useful (but not necessary) to put the called methods first so when you read the code you know you can find the definitions of called methods above.

dlask
  • 8,776
  • 1
  • 26
  • 30