Global - Static method vs module function in python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

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 *.

http://docs.python.org/tutorial/modules.html#importing-from-a-package http://docs.python.org/tutorial/modules.html#importing-from-a-package

__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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/3570823/static-method-vs-module-function-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils