Python Class Layout – Conventions and Best Practices

object-orientedpython

What is the proper or standard way to layout a class. If a class where to have attributes, methods, private attributes, private methods, class property (methods), and class methods. I am done 99% of my coding procedurely and beyond working with ORM haven't focused to much on OOP. I am changing that in a current project and was just curios what the standard way of organizing your classes was.

Class MyClass():
   attr1 = value1
   attr2 = value2
   _attr3 = value3
   def __init__(self):
      do some stuff
   def do_something(self):
      do some more stuff

   def __do_something_else(self):
      more stuff
   @property()
   def attr4(self):
       return do_some_stuff_else()

   @classmethod()
   def generator_a_bunch_of_these(cls):
       do_some_more_things

Best Answer

Look for such answers in here: http://www.python.org/dev/peps/

Basics is in the most famous one: http://www.python.org/dev/peps/pep-0008/

By the looks and code i have seen, you got pretty good idea about that. Good luck, hope it'll help :)

UPDATE: While following pep rules you come up with about the same anyway :) so pure convention for classes - yes there is none or i haven't heard of it. How you should write it - pep8. By common programming sense you write you variables, fields above methods. Same things happen with everything else. Just code as the Holy Zen of Python teaches you:

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently. Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one - and preferably only one - obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea - let's do more of those!
Related Topic