python - should I use static methods or top-level functions

后端 未结 5 1374
小蘑菇
小蘑菇 2020-12-23 14:01

I come from a Java background and I\'m new to python. I have a couple scripts that share some helper functions unique to the application related to reading and writing file

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 14:48

    From the Zen of Python (import this) :

    Namespaces are one honking great idea -- let's do more of those!
    

    One of the main reasons to create static methods in a language like Java is to ensure that those methods don't wind up polluting the global namespace. (Although Java enforces its own namespace conventions by disallowing "package-level" functions entirely !) In Python, all "top-level" functions are automatically placed within the namespace of the module containing those functions, so there's no danger of polluting the global namespace this way.

    In other words, like many other languages, Python can create namespaces in a few different ways. In this case, there's little need to create a class containing only static methods, when a module serves the same namespacing purpose without the clutter (or cognitive load) associated with defining a class.

提交回复
热议问题