Naming rules for variables in python, python Variables

Source: Internet
Author: User

Naming rules for variables in python, python Variables

From: http://www.diybl.com/course/3_program/python/20111130/563643.html
Module name:
Lowercase letters, separated _
Ad_stats.py

Package Name:
Same as module name

Class Name:
Uppercase letters
AdStats
ConfigUtil

Global variable name (class variable, equivalent to static variable in java ):
Uppercase letters, separated _
NUMBER
COLOR_WRITE

Common variables:
Lowercase letters, separated _
This_is_a_var

Instance variables:
Start with _. Others are the same as normal variables.
_ Price
_ Instance_var

Private instance variable (an error is reported during external access ):
It must start with _ (2 underscores), and the others are the same as normal variables.
_ Private_var

Private variables:
Start with _, end with __, which is generally a python variable. Do not name it in this way.
_ Doc __
_ Class __

Common functions:
Same as common variables:
Get_name ()
Count_number ()
Ad_stat ()

Private function (an error is reported during external access ):
It must start with _ (2 underscores), and the others are the same as normal functions.
_ Get_name ()
--------------------------------------------------------------------
File Name
Lowercase letters, underlines
Package
It should be a short and lowercase name. You can add underscores to improve readability. For example, mypackage.
Module
The same as the package specification. For example, mymodule.
Class
Always use an uppercase string of words. For example, MyClass. Internal classes can use extra leading underlines.

Functions & Methods
The function name should be in lower case. You can use underlined words to increase readability. For example, myfunction and my_example_function.
* Note *: the mixed case is only allowed when this style is already dominant to maintain backward compatibility.
Function and method parameters
"Self" is used as the first parameter of the instance method. "Cls" is used as the first parameter of the class method.
If the parameter name of a function conflicts with the reserved keyword, it is usually better to use a suffix underline than to use abbreviations or strange spelling.
Global Variables
For the from M import * import statement, if you want to prevent global variables in the import module, you can use the old specification to add a leading underline to the global variables.
* Note *: Avoid using global variables.
Variable
All variable names are in lowercase, and each word is connected by an underscore. Such as color = WHITE, this_is_a_variable = 1
* Note *:
1. No m or g prefix is used for both class member variables and global variables.
2. Private class members are identified by a single underline prefix. Multiple public members are defined and less private members are defined.
3. Variable names should not contain type information, because Python is a dynamic type language. For example, iValue, names_list, and dict_obj are all poorly named.
Constant
All the letters of a constant name are capitalized, and each word is connected by an underscore, such as MAX_OVERFLOW and TOTAL.
Exception
Use "Error" as the suffix.
Abbreviations
You should try to use all words for naming. The abbreviations are as follows:
1. Common abbreviations, such as XML and ID, should also be capitalized, such as XmlParser.
2. The name contains long words, which are abbreviated to a word. In this case, we should use the abbreviated form of conventions.
For example:
Function is abbreviated as fn.
The abbreviation of text is txt.
Object is abbreviated as obj.
Count stands for cnt
Number is abbreviated as num.
Leading suffix underline
A leading underline: non-public.
One suffix underline: Avoid keyword conflict.
Two leading underscores (_): used to name a class attribute that causes Name Conflict.
Two leading and suffix underscores (_ init _ or _ file _): "magic" (for special purposes) objects or attributes __. Never create such names, but use them.
* Note *: the use of underlines is controversial.
Python uses underlines as the prefix and suffix of variables to specify special variables.

_ Xxx cannot be imported using 'from module import *'
_ Xxx _ system definition name
_ Private variable name in xxx class

Core style: Avoid using underscores as the start of variable names.

Because underlines have special meanings for the interpreter and are symbols used by built-in identifiers, we recommend that programmers avoid using underscores as the beginning of the variable name. Generally, variable name_xxx is considered as "private" and cannot be used outside the module or class. When the variable is private, it is a good habit to use _ xxx to represent the variable. For Python, the variable name _ xxx _ is confusing and confusing. Why is it difficult to create a variable? Br>
The member variables starting with "single underline" are called protection variables, meaning that only class objects and subclass objects can access these variables themselves;
"Double underline" begins with a private member, which means that only the class object can access the data, and even the subclass object cannot access the data.

A class attribute that starts with a single underscore (_ foo) represents a class attribute that cannot be accessed directly. It must be accessed through the interface provided by the class. It cannot be imported using "from xxx import; (_ foo) starting with a double underline represents a private member of the class; (_ foo _) Starting with and ending with a double underline represents a special identifier for special methods in python, for example, _ init _ () indicates the constructor of the class.
Specific naming method
It mainly refers to the system reserved wordname method in the form of _ xxx. This type of name can also be used in projects. It means that variables in this form are read-only, and class member functions in this form should not be overloaded as much as possible. For example
Class Base (object ):
Def _ init _ (self, id, parent = None ):
Self. _ id _ = id
Self. _ parent _ = parent
Def _ message _ (self, msgid ):
#... Omitted
Both _ id _, _ parent _, and _ message _ use the system reserved name.
Appendix: Google Python naming rules
Module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name.
--------------------------------------------------------
From: http://hi.baidu.com/kxw102/blog/item/212e9f3859202fe33b87ce4b.html
Understand the Python naming mechanism

Introduction
I warmly invite you to guess the output of the following program:
Class A (object ):
Def _ init _ (self ):
Self. _ private ()
Self. public ()
Def _ private (self ):
Print 'a. _ private ()'
Def public (self ):
Print 'a. public ()'
Class B ():
Def _ private (self ):
Print 'B. _ private ()'
Def public (self ):
Print 'B. public ()'
B = B ()

Preliminary Exploration
The correct answer is:
A. _ private ()
B. public ()
If you have guessed it, you can skip this blog. If you haven't guessed it or have some questions, I have prepared this blog for you.
The reason for the output is "A. _ private. But to clarify why, we need to understand the Python naming mechanism.
According to Python manual, the variable name (identifier) is an atomic element of Python. When a variable name is bound to an object, the variable name refers to this object, just like in human society, isn't it? When the variable name appears in the code block, it is the local variable; when the variable name appears in the module, it is the global variable. I believe everyone has a good understanding of the module, but the code block may be confusing. Here we will explain:
A code block is a piece of Python program text that can be used as an executable unit. modules, function bodies, and class definitions are all code blocks. In addition, each interactive script command is also a code block, a script file is also a code block, and a command line script is also a code block.
Next we will talk about the visibility of variables. We will introduce the concept of a range. The range is the visibility of variable names in the code block. If a code block defines local variables, the range includes this code block. If a variable is defined in a function code block, the range is extended to any code block in the function block unless another variable with the same name is defined. But the scope of variables defined in the class is limited to the class code block, instead of being extended to the method code block.

Lost
According to the theory above, we can divide the code into three code blocks: Class A, Class B, and variable B. According to the class definition, we know that the Code defines three member variables for Class A (Python functions are also objects, so the Member methods can also be called member variables .); Class B defines two member variables. This can be verified by the following code:
>>> Print '\ n'. join (dir ())
_ A _ private
_ Init __
Public
>>> Print '\ n'. join (dir (B ))
_ A _ private
_ B _ private
_ Init __
Public
Why does Class A have an Attribute named _ A _ private? And _ private disappears! Now let's talk about the rolling of Python's private variables.

Exploration
Anyone familiar with Python knows that Python treats a variable that starts with two or more underscores and does not end with two or more underscores as a private variable. Private variables are converted to long format (public) before code generation ). The conversion mechanism is as follows: insert the class name at the front end of the variable, and add an underline character at the front end. This is the so-called Private name mangling ). For example, the _ private identifier in Class A will be converted to _ A _ private, which is why _ A _ private and _ private disappear in the previous section.
Let's talk about two more things:
First, the identifier is longer due to rolling. When it exceeds 255, Python will cut off. Note the naming conflict caused by this.
Second, when all the class names are named below, Python will not execute rolling. For example:
>>> Class ____ (object ):
Def _ init _ (self ):
Self. _ method ()
Def _ method (self ):
Print '____. _ method ()'
>>> Print '\ n'. join (dir (____))
_ Class __
_ Delattr __
_ Dict __
_ Doc __
_ Getattribute __
_ Hash __
_ Init __
_ Method # not rolled
_ Module __
_ New __
_ Reduce __
_ Performance_ex __
_ Repr __
_ Setattr __
_ Str __
_ Weakref __
>>> Obj = ____()
____. _ Method ()
>>> Obj. _ method () # can be called externally
____. _ Method ()
Now let's look at why "A. _ private ()" is output!

Truth
I believe that smart readers have already guessed the answer? If you haven't thought of it, I will give you a prompt: The truth is similar to macro preprocessing in C language.
Because Class A defines A private member function (variable), execute the private variable rolling before the code is generated (note that the line marked with red in the previous section does not exist ?). After the rolling, the code of Class A becomes like this:
Class A (object ):
Def _ init _ (self ):
Self. _ A _ private () # This line has changed
Self. public ()
Def _ A _ private (self): # This line has also changed
Print 'a. _ private ()'
Def public (self ):
Print 'a. public ()'
Is it a bit like the macro development in C language?
Because the _ init _ method is not overwritten when class B is defined, the call is still. _ init __, that is, self. _ A _ private (), which naturally outputs ". _ private.
The following two sections of code increase persuasiveness and increase understanding:
>>> Class C ():
Def _ init _ (self): # rewrite _ init __and no longer call self. _ A _ private
Self. _ private () # _ C_private is bound here.
Self. public ()
Def _ private (self ):
Print 'C. _ private ()'
Def public (self ):
Print 'C. public ()'
>>> C = C ()
C. _ private ()
C. public ()
############################
>>> Class A (object ):
Def _ init _ (self ):
Self. _ A _ private () # Call an undefined function. Python will give it to my handler _^ ~
Self. public ()
Def _ private (self ):
Print 'a. _ private ()'
Def public (self ):
Print 'a. public ()'
>>> A = ()
A. _ private ()
A. public ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.