Using static methods in python - best practice

后端 未结 4 1759
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 20:24

When and how are static methods suppose to be used in python? We have already established using a class method as factory method to create an instance of an object should be

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 21:05

    Your first example makes the most sense to me: Entity.from_id is pretty succinct and clear.

    It avoids the use of data in the next two examples, which does not describe what's being returned; the data is used to construct an Entity. If you wanted to be specific about the data being used to construct the Entity, then you could name your method something like Entity.with_data_for_id or the equivalent function entity_with_data_for_id.

    Using a verb such as find can also be pretty confusing, as it doesn't give any indication of the return value — what is the function supposed to do when it's found the data? (Yes, I realize str has a find method; wouldn't it be better named index_of? But then there's also index...) It reminds me of the classic:

    find x

    I always try to think what a name would indicate to someone with (a) no knowledge of the system, and (b) knowledge of other parts of the system — not to say I'm always successful!

提交回复
热议问题