Non-member vs member functions in Python

前端 未结 5 1819
清歌不尽
清歌不尽 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 22:20

    Look at your own example - the non-member function has to access the data members of the Vector class. This is not a win for encapsulation. This is especially so as it changes data members of the object passed in. In this case, it might be better to return a scaled vector, and leave the original unchanged.

    Additionally, you will not realise any benefits of class polymorphism using the non-member function. For example, in this case, it can still only cope with vectors of two components. It would be better if it made use of a vector multiplication capability, or used a method to iterate over the components.

    In summary:

    1. use member functions to operate on objects of classes you control;
    2. use non-member functions to perform purely generic operations which are implemented in terms of methods and operators which are themselves polymorphic.
    3. It is probably better to keep object mutation in methods.

提交回复
热议问题