Non-member vs member functions in Python

前端 未结 5 1798
清歌不尽
清歌不尽 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条回答
  •  梦毁少年i
    2021-02-18 22:09

    Interesting question.

    You're starting from a different place than most questions coming from Java programmers, which tend to assume that you need classes when you mostly don't. Generally, in Python there's no point in having classes unless you're specifically doing data encapsulation.

    Of course, here in your example you are actually doing that, so the use of classes is justified. Personally, I'd say that since you do have a class, then the member function is the best way to go: you're specifically doing an operation on that particular vector instance, so it makes sense for the function to be a method on Vector.

    Where you might want to make it a standalone function (we don't really use the word "member" or "non-member") is if you need to make it work with multiple classes which don't necessarily inherit from each other or a common base. Thanks to duck-typing, it's fairly common practice to do this: specify that your function expects an object with a particular set of attributes or methods, and do something with those.

提交回复
热议问题