简体   繁体   中英

How should I arrange methods in a class in Python?

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.

我首选的是先放置__init__方法,然后按字母顺序分配其他方法。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM