Naming conventions for variables in Python

Source: Internet
Author: User

Originating From: http://www.diybl.com/course/3_program/python/20111130/563643.html
Module Name:
Lowercase letters, dividing between words with _
ad_stats.py

Package Name:
Same as the module name

Class Name:
Capitalize the first letter of the word
Adstats
Configutil

global variable names (class variables, equivalent to static variables in Java):
Uppercase letters, dividing between words with _
Number
Color_write

Common variables:
Lowercase letters, dividing between words with _
This_is_a_var

Instance variable:
Start with _, the rest is the same as the normal variable
_price
_instance_var

Private instance variable (external access will error):
Starts with __ (2 underscores), and the other is the same as the normal variable
__private_var

Proprietary variables:
__ Begins, __ ends, is usually python's own variable, do not name it in this way
__doc__
__class__

Common functions:
As with normal variables:
Get_name ()
Count_number ()
Ad_stat ()

Private function (external access will error):
Starts with __ (2 underscores), and the rest is the same as the normal function
__get_name ()
————————————————————————————————————————————————————————————————————
Filename
Full lowercase, underline available
Package
It should be a short, lowercase name. If the underline can improve readability can be added. such as MyPackage.
Module
Same as the specification of the package. such as MyModule.
Class
Always capitalize the word string with the first letter. such as MyClass. The inner class can use additional leading underscores.

Functions & Methods
The function name should be lowercase, and underline-style words can be used to increase readability. such as: Myfunction,my_example_function.
* Note *: Mixed case is only allowed to be used when this style has taken advantage, in order to remain backwards compatible.
Parameters for functions and methods
Always use "self" as the first parameter of an instance method. Always use "CLS" as the first parameter of a class method.
If a function's parameter name conflicts with reserved keywords, it is usually better to use a suffix underline than to use abbreviations or strange spellings.
Global variables
For from M Import * Import statements, if you want to prevent global variables within the import module from using the old specification, add a leading underscore to the global variable.
* NOTE *: You should avoid using global variables
Variable
Variable names are all lowercase, and each word is concatenated by an underscore. such as color = White,this_is_a_variable = 1
* Note *:
1. Neither the class member variable nor the global variable uses the M or G prefixes.
2. Private class members are identified with a single underscore prefix, multiple definitions expose members, and less private members are defined.
3. Variable names should not have type information, because Python is a dynamic type language. such as Ivalue, Names_list, dict_obj, etc. are not a good name.
Constant
The constant name is all letters capitalized, and each word is connected by an underscore, such as max_overflow,total.
Abnormal
Use "Error" as the suffix.
Abbreviation
The name should use all spelling words as far as possible, the abbreviation is as follows two kinds of things:
1. Commonly used abbreviations, such as XML, ID, and so on, should be named with only the first letter, such as Xmlparser.
2. The name contains long words, and a word is abbreviated. You should use the abbreviated method of the contract idiomatic.
For example:
function abbreviation is FN
Text abbreviation for TXT
The object abbreviation is obj
Count abbreviation for CNT
Number is abbreviated to NUM, and so on.
Leading suffix underline
A leading underscore: represents a non-public.
One suffix underscore: avoid keyword collisions.
Two leading underscores: used when naming a class property that causes a name conflict.
Two leading and suffix underscores: "Magic" (with special-purpose) objects or attributes, such as __init__ or __file__. Never create names like this, just use them.
* NOTE *: There is some controversy about the use of underscores.
PYTHON specifies special variables with underscores as variable prefixes and suffixes.

_xxx cannot be imported with ' from module import * '
__xxx__ System Definition Name
Private variable names in the __xxx class

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

Because underscores have special meanings for the interpreter and are symbols used by built-in identifiers, we recommend that programmers avoid using underscores as the starting point for variable names. In general, variable name _xxx is considered "private" and cannot be used outside of a module or class. When a variable is private, it is good practice to use _xxx to represent variables. Because the variable name __xxx__ to Python having Chan swell disables plot pit φ North Acenaphthene Mr. Tuo an lock browsing?br>
A member variable that starts with a "single underline" is called a protection variable, meaning that only class objects and subclass objects can access these variables themselves;
A "double underline" begins with a private member, meaning that only the class object can access it, and the child object cannot access the data.

A class attribute that begins with a single underscore (_foo) cannot be accessed directly, and is accessed through the interface provided by the class, cannot be imported with a "from XXX import *", and a double underscore (__foo) represents a private member of the class; A double underscore that starts and ends (__foo__ Represents a special method-specific identifier for Python, such as __init__ (), which represents the constructor of a class.
Specific naming methods
Mainly refers to the __xxx__ form of the system reserved word naming method. This type of naming can also be used in projects, meaning that variables of this form are read-only and this form of class member functions is not overloaded as much as possible. Such as
Class Base (object):
def __init__ (self, id, parent = None):
self.__id__ = ID
self.__parent__ = Parent
def __message__ (self, MsgId):
# ... Slightly
Among them, __id__, __parent__ and __message__ all adopt the system reserved word naming method.
Attached: Google python naming conventions
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
Understanding 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 (A):
def __private (self):
print ' b.__private () '
def public (self):
print ' B.public () '
b = B ()

Of
The correct answer is:
A.__private ()
B.public ()
If you have guessed right, then you can not read my blog post. If you have not guessed right or have doubts in your mind, then my this piece of Bo Wenzheng is for you to prepare.
It all starts with the output of "a.__private ()". But to make it clear why, it is necessary to understand the naming mechanism of Python.
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 the object, just like human society, isn't it? When the variable name appears in the code block, it is a local variable, and when the variable name appears in the module, it is the global variable. The module believes everyone has a good understanding, but the code block may be confusing. Here's a little bit of explanation:
A block of code is a Python program text that can be used as an executable unit, and a module, a function body, and a class definition are blocks of code. Not only that, each interactive script command is also a block of code; a script file is also a block of code; a command-line script is also a block of code.
Next we talk about the visibility of variables, and we introduce a concept of scope. The scope is the visibility of the variable name in the code block. If a local variable is defined in a code block, the range includes this block of code. If a variable is defined in a function code block, that range extends to any block of code in the function block unless it defines another variable with the same name. However, the scope of a variable defined in a class is scoped to the class code block, not to the method code block.

Mystery
According to the theory of the previous section, we can divide the code into three code blocks: the definition of Class A, the definition of Class B, and the definition of variable B. According to the class definition, we know that the code defines three member variables for Class A (the Python function is also an object, so the member method is called a member variable, which also makes sense.) ), Class B defines two member variables. This can be verified by the following code:
>>> print ' \ n '. Join (dir (A))
_a__private
__init__
Public
>>> print ' \ n '. Join (dir (B))
_a__private
_b__private
__init__
Public
Gee, why does Class A have a Attribute named _a__private? And __private's gone! This is about Python's private variable rolling.

Explore
A friend of Python knows that Python treats a variable that begins with two or an underscore character and does not end in two or an underscore as a private variable. Private variables are converted to long-form (public) before the code is generated. The conversion mechanism is this: Insert the class name at the front of the variable, and then add an underscore character to the front end. This is known as private variable rolling (private name mangling). The __private identifier in class A will be converted to _a__private, which is why the _a__private and __private disappeared in the previous section.
Let's talk about the two-point topic:
One is because the pressure will make the identifier longer, when more than 255, Python will be cut off, pay attention to the resulting naming conflicts.
The second is that when the class name is all underlined, Python no longer performs a rolling. Such as:
>>> class ____ (object):
def __init__ (self):
Self.__method ()
def __method (self):
print ' ____.__method () '
>>> print ' \ n '. Join (dir (___))
__class__
__delattr__
__dict__
__doc__
__getattribute__
__hash__
__init__
__method # has not been crimped
__module__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__str__
__weakref__
>>> obj = ____ ()
____.__method ()
>>> Obj.__method () # can be called externally
____.__method ()
Now let's look back and see why the output is "a.__private ()"!

The truth
Believe that the smart reader has guessed the answer now? If you haven't thought about it, I'll give you a hint: the truth is similar to the macro preprocessing in C.
Because Class A defines a private member function (variable), the private variable rolling is performed before the code is generated (notice the line of the previous section marked red?). )。 After rolling, the code for Class A becomes this:
Class A (object):
def __init__ (self):
Self._a__private () # This is the same line.
Self.public ()
def _a__private (self): # This line has changed.
print ' a.__private () '
def public (self):
print ' A.public () '
Is it a bit like the macro expansion in C language?
Because the __init__ method is not overwritten when the class B is defined, the call is still a.__init__, that is, the self._a__private () is executed, and the natural output is "a.__private ()".
The following two pieces of code can increase persuasion and improve understanding:
>>> class C (A):
def __init__ (self): # rewrite __init__, no longer calls Self._a__private
Self.__private () # It's bound to be _c_private.
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 a function that is not defined, Python will give it to my ^_^ ~
Self.public ()
def __private (self):
print ' a.__private () '
def public (self):
print ' A.public () '
>>>a = A ()
A.__private ()
A.public ()

Naming conventions for variables in Python

Related Article

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.