Non-member vs member functions in Python

前端 未结 5 1797
清歌不尽
清歌不尽 2021-02-18 21:54

I\'m relatively new to Python and struggling to reconcile features of the language with habits I\'ve picked up from my background in C++ and Java.

The latest issue I\

5条回答
  •  情歌与酒
    2021-02-18 21:54

    A free function gives you the flexibility to use duck-typing for that first parameter as well.

    A member function gives you the expressiveness of associating the functionality with the class.

    Choose accordingly. Generally, functions are created equal, so they should all have the same assumptions about the interface of a class. Once you publish a free function scale, you are effectively advertising that .dX and .dY are part of the public interface of Vector. That is probably not what you want. You are doing this in exchange for the ability to reuse the same function with other objects that have a .dX and .dY. That is probably not going to be valuable to you. So in this case I would certainly prefer the member function.

    For good examples of preferring a free function, we need look no further than the standard library: sorted is a free function, and not a member function of list, because conceptually you ought to be able to create the list that results from sorting any iterable sequence.

提交回复
热议问题