Static method vs module function in python

2019-04-21 12:55发布

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?

3条回答
做个烂人
2楼-- · 2019-04-21 13:31

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.

查看更多
做个烂人
3楼-- · 2019-04-21 13:32

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.

查看更多
smile是对你的礼貌
4楼-- · 2019-04-21 13:36

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

查看更多
登录 后发表回答