开发者

How should I arrange methods in a class in Python?

How should (o开发者_StackOverflow社区r 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.


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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜