Module function vs staticmethod vs classmethod vs no decorators: Which idiom is more pythonic?

前端 未结 4 1439
既然无缘
既然无缘 2020-11-29 18:35

I\'m a Java developer who\'s toyed around with Python on and off. I recently stumbled upon this article which mentions common mistakes Java programmers make when they pick u

4条回答
  •  [愿得一人]
    2020-11-29 19:14

    The best answer depends on how the function is going to be used. In my case, I write application packages that will be used in Jupyter notebooks. My main goal is to make things easy for the user.

    The main advantage of function definitions is that the user can import their defining file using the "as" keyword. This allows the user to call the functions in the same way that they would call a function in numpy or matplotlib.

    One of the disadvantages of Python is that names cannot be protected against further assignment. However, if "import numpy as np" appears at the top of the notebook, it's a strong hint that "np" should not be used as a common variable name. You can accomplish the same thing with class names, obviously, but user familiarity counts for a lot.

    Inside the packages, however, I prefer to use static methods. My software architecture is object oriented, and I write with Eclipse, which I use for multiple target languages. It's convenient to open the source file and see the class definition at the top level, method definitions indented one level, and so on. The audience for the code at this level is mainly other analysts and developers, so it's better to avoid language-specific idioms.

    I don't have a lot of confidence in Python namespace management, especially when using design patterns where (say) an object passes a reference to itself so that the called object can call a method defined on the caller. So I try not to force it too far. I use a lot of fully qualified names and explicit instance variables (with self) where in other languages I could count on the interpreter or the compiler managing the scope more closely. It's easier to do this with classes and static methods, which is why I think they are the better choice for complex packages where abstraction and information hiding are most useful.

提交回复
热议问题