What is the naming convention in Python for variable and function names?

后端 未结 13 2258
生来不讨喜
生来不讨喜 2020-11-22 08:50

Coming from a C# background the naming convention for variables and method names are usually either camelCase or PascalCase:



        
相关标签:
13条回答
  • 2020-11-22 09:28

    See Python PEP 8: Function and Variable Names:

    Function names should be lowercase, with words separated by underscores as necessary to improve readability.

    Variable names follow the same convention as function names.

    mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

    0 讨论(0)
  • 2020-11-22 09:31

    There is PEP 8, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.

    0 讨论(0)
  • 2020-11-22 09:32

    The Google Python Style Guide has the following convention:

    module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name.

    A similar naming scheme should be applied to a CLASS_CONSTANT_NAME

    0 讨论(0)
  • 2020-11-22 09:33

    Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.

    0 讨论(0)
  • 2020-11-22 09:33

    There is a paper about this: http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf

    TL;DR It says that snake_case is more readable than camelCase. That's why modern languages use (or should use) snake wherever they can.

    0 讨论(0)
  • 2020-11-22 09:34

    The coding style is usually part of an organization's internal policy/convention standards, but I think in general, the all_lower_case_underscore_separator style (also called snake_case) is most common in python.

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