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
1 Answer 1
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!
-
1I have read through these documents prior to my question and did find a wealth of good information however none that addressed the question of how the class should be physically laid out. Perhaps a convention doesn't exist and I just need to make some rules for our office on how we want to do it.Ominus– Ominus06/06/2011 13:53:04Commented Jun 6, 2011 at 13:53
-
1I've just updated my answer, o thought to reply a comment but then i realized that its more of an update and clarification.JackLeo– JackLeo06/06/2011 14:04:37Commented Jun 6, 2011 at 14:04
attr1
,attr2
and_attr3
) is often a very bad idea. Folks who come from languages with static declarations are sometimes confused by this and think that these class-level attributes somehow important. Also, 80% of the time, you want@staticmethod
not@classmethod
.