Static method vs module function in python

2019-04-21 12:30发布

问题:

So I have a class in a module that has some static methods. A couple of these static methods just do crc checks and stuff, and they're not really useful outside of the class (I would just make them private static methods in java or C++). I'm wondering if I should instead make them global class functions (outside of the class).

Is there any benefit for doing it either way? The class is being imported by from module import class so I'm not worried about having those modules pulled in as well. But should I just make them class methods so that from module import * is safer or something?

回答1:

Prefixing the function names with a single underscore is a convention to say that they are private, and it will also prevent them from being imported with a from module import *.

Another technique is to specify an __all__ list in the module - this can just be done in the module itself (you don't need an __init__.py file)

__all__ = ['my_class_name']

This is more of a whitelist approach, so you can have full control over what gets imported without using leading underscores.

So unless your methods logically belong in the class, and from your description they don't, I would leave them as module level functions and use one of these two approaches to make them private.



回答2:

Make them module-level functions, and prefix them with a single underscore so that consumers understand that they are for private use.



回答3:

If they are not useful outside of the class, what is the motivation to make them module methods? Keeping them as static method makes the name space cleaner.

The only advantage to move it outside maybe so that people can reference them without using qualified them the class name. Say you have a log method that got reference in a ton of places, this may make sense as a stylistic choice.