Is it a convention to prefix private classes with underscores?

后端 未结 4 1042
小鲜肉
小鲜肉 2021-01-17 22:35

I have seen code in which functions/constants are prefixed with underscores. My understanding is that this indicates that they are not to be used directly. Can I do this wit

相关标签:
4条回答
  • 2021-01-17 22:51

    Yes, and this is not only a convention. When you import * from this module, names starting with underscore will not be imported.

    0 讨论(0)
  • 2021-01-17 22:53

    Better only use one _. This indicates that a name is private within a module.

    It is not imported with the catch-all from <module> import *, and it has some other features such as "preferred destruction".

    From here:

    If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_').

    From here:

    Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted.

    Double-underscore starting class members are name-mangled.

    0 讨论(0)
  • 2021-01-17 23:01

    Yes; the single underscore usage is endorsed by PEP8 for internal-use classes.

    I don't believe the double underscore usage will have any real effect most of the time, since it's used to active name mangling for class attributes, and generally a class isn't an attribute of another class (granted, it can be, in which case Python will happily mangle the name for you.)

    0 讨论(0)
  • 2021-01-17 23:08

    You can use a single underscore as the first character in any variable, but it is carries the implied meaning, "Do not use outside of the class/module unless you really know what you're doing" (eg. intended protected/internal) and it will not import if you use from <module> import *.

    Using a double underscore is something you should never do outside of a class as it could mess with name mangling otherwise (and by "could", I mean, "caused me a big headache this past week because I did not realize that it does").

    0 讨论(0)
提交回复
热议问题