Python advanced Programming Selection Good name: Pepe8 and naming best practices

Source: Internet
Author: User
Tags naming convention

# #-*-Coding:utf-8-*-

# # python:2.x

# __author__ = ' Administrator '

# my_list=[' A ', ' B ', ' C ', ' d '

# """

# Most standard programs are built without ignoring usability, see the following example to understand the meaning of the sentence

# """

# if ' e ' not in my_list:

# my_list.append (' E ')

# Print My_list

# #[' A ', ' B ', ' C ', ' d ', ' e ']

# #这是编写python程序和其他语言相比更加简单的原因之王, when writing a program, ideas can quickly be converted into lines of code

# #3点是本章的重点

# """

# Use the naming conventions described in Pep8, and a set of naming best practices

# namespace Refactoring

# using the API, from the initial model to its refactoring model

# """

# #pepe8和命名最佳实践: Address: www.python.org/dev/peps/pepe-008, provides some guidelines related to coding style

# #不同的命名风格包括

# """

# CamelCase (capitalize each word)

# minedcase is similar to CamelCase, but the first word is still lowercase

# Uppercase (uppercase), and er_case_with_underscores (uppercase and underlined)

# lowercase (lowercase) and lower_case_with_underscores (lowercase and underlined)

# prefix (_leading) and suffix (trailing_) underline or both underline (__doubled__)

# lowercase and uppercase elements are usually a word, using underscores are usually abbreviations, and using words is better, prefixes and suffixes are used to mark private and special elements

# """

# #变量

# #常量: Do not change global variables, use uppercase and an underscore, tell us that the variables specified by the developer represent a constant value

# #注意: There is no real constant in Python-c++ defines that constant with const, and any variable can be modified, which is why Python uses a naming convention to mark a variable as constant

# """

# For example, the Doctest module provides a list of option flags and directives (refer to http://docs.python.org/lib/doctest-options.html)

# """

# from Doctest import ignore_exception_detail,report_only_first_failure

# #虽然变量名看上去相当长, it's important to have a clear description of them, basically using them in the initialization code, not in the body of the code itself, so lengthy names are not annoying

# #大部分的情况, abbreviated names can blur the code, and don't be afraid to use the full statement when the abbreviated name is not clear enough

# #一些常量的名称也是基于低层技术派生的, for example

# import OS

# try:

# os._exit (0)

# except OS. Ex_software:

# print ' interanl sortwar error '

# Raise

# #使用常量时, it's a good idea to focus them on the head of the module, which should be grouped under a new variable when used for the following actions

# test_optinos= (ellipsis| ignore_exception_detail| Report_only_first_failure)

# #命名和使用

# #常量用来定义一组程序所依赖的值, such as the default profile name, it's a good idea to centralize all the constants in a separate file in the package

# #config. py

# sql_user= ' Tarek '

# sql_password= ' Secret '

# sql_url= ' postgres://%s:%[email protected]/db '% (Sql_user,sql_password)

# max_threads=4

# #另一种方法是使用ConfigParser或者ZConfig (Advanced) module tools (used in Zope to describe its profile resolver) parse the configuration file, in Python such program files can be as easy to edit and modify the language as a text file, Using this method is too much for another file format

# #对于表现的像标志选项, it's a good way to combine them with Boolean operations, like the doctest and re modules, as follows

# options={}

# def REG (name):

# return Options.setdefault (Name,1<<len (OPTIONS))

# def HASG (options,name):

# return bool (options&name)

# #现在定义选项

# A=reg (' A ')

# B=reg (' B ')

# C=reg (' C ')

#

# #然后尝试它们

# s=a| B

# print HASG (s,a)

# #当创建这样一组新的常量时, you should avoid using a constant prefix, unless there are many groups in the module, the module name itself is a common prefix

# "" In Python, combining options using binary bitwise calculations is commonly seen in methods, using or (|) Operators can combine multiple options in an integer, and the (&) operator can check options in integers, referring to the HASG function above

# If this integer can be shifted using the << operator to ensure that the combination gets another difference in the integer, it works, in other words, it is a power of 2 (refer to Reg)

# """

# #公有和私有变量

# #对于易变和仅有全局变量, they should use lowercase and an underscore when they need to be protected, but such variables are not commonly used because the module typically provides gettert,setter to handle them when protection is required, in which case a leading underscore indicates that the variable is a private element of the package As follows:

# _bao=[]

# def Add_bao (Bao):

# _bao.append (Bao)

# def Get_bao ():

# ' makes sure _bao cannot be modified. '

# return tuple (_bao)

# #位于函数和方法中变量遵循相同的规则 and will never be flagged as private because they are local to the context

# #对于类或者实例变量而言, a private flag (that is, a leading underscore) must be used only if the variable is part of a public signature and does not bring any useful information or redundancy

# #换锯话说, if the variable is used inside a method to provide a common feature and only plays this role, it is better to declare the total as private, as follows

# #只支持一个属性的是好的私有成员

# class C (object):

# def __init__ (self):

# self._message= ' Go '

# def _get_mess (self):

# return Self._message

# Kane=property (_get_mess)

#

# print C (). Kane

# #另一个例子是用来保持内部状态的变量, this value is useless for the rest of the code, but it participates in the behavior of the class, as follows

# class M (object):

# def __init__ (self):

# self._peple_to_kill=[]

# def is_slapped_on_the_button_by (Self,ane):

# self._peple_to_kill.append (ANE)

# print ' ouch! '

# def reveget (self):

# print ' Ten year later ... '

# for P in Self._peple_to_kill:

# print '%s '%p

# a=m ()

# Print a.is_slapped_on_the_button_by (' Tarek ')

# Print A.reveget ()

# #不要轻易断言类进行子类化时可用采用的方式

# #函数和方法

# #命名时应该使用小写和下划线, but not always follow this rule in the standard library, you can find some using mixed case (mixedcase) modules, using the CurrentThread in threading (which may change in python3000 )

# #这样的编写方法的方式在小写范式成为标准之前很常见, frameworks such as Zope also use a mixed-case approach that uses a large developer base, so what to choose between mixed case and lowercase underlines depends largely on the library you are using

# #在这样的类型程序库环境中, the most orthodox method is only for elements that are exported to the frame and mixed case, and other code remains as pep-style

# #1关于私有元素的争论

# """

# for private methods and functions, the naming inertia is to add a leading underscore, which is quite controversial given the Python name adaptation feature, and the interpreter immediately renames the method when it has 2 leading underscores to avoid conflicts with methods in subclasses

# as follows

# """

Class Base (object):

def __secret (self):

print ' 1 '

def public (self):

Self.__secret ()

# #print Base.__secret () Attributeerror:type object ' Base ' has no attribute ' __secret '

Print dir (Base)

Class B1 (Base):

def __secret (self):

print ' New ver '

B1 (). Public ()

The original motive of the #python中设计名称改编 (name mailing) is not to provide a private body (gimmick) similar to C + +, but to ensure that some base classes implicitly avoid closing windows in subclasses, especially in multi-inheritance environments, but if you use it for each attribute, will make the code blurry, it's not Python-style at all.

#有些人认为应该始终使用显式名称, adapted, as below, _a (self) to do otherwise

Class AA (object):

def _a (self):

Pass

#该类将在整个代码中不断重复, because __ is the preferred

#正如BDFL (Guido,benevloent dictator for Life, reference: EN.WIKIPEDIA.ORG/WIKI/BDFL), is to avoid name adaptations by looking at the __mro__ before writing methods in subclasses. Private methods that change the base class must be carefully

#具体可以看下http: Find on//mail.python.org/pipermail/python-dev/2005-december/058555.html

#BENEVLOENT Dictator for life (that is, mercy the Great)

#特殊方法: docs.python.org/ref/specialnames.html, which starts and ends with 2 underscores, the general method should not use this naming convention, is used for operator overloading, and so on, as follows

Class W (int):

def __add__ (self, Other):

Return int.__add__ (Self,other) +1

def __repr__ (self):

Return ' weibor%d '%self

#

#公有api

#

def do_this (self):

print ' This '

def do_that (self):

print ' That '

#对于常用的方法, this name should never be used, so do not create the following name method;

Class Ba (object):

def __my_methond__ (self):

Pass

#参数: Use lowercase and underline if necessary, they follow the same naming rules as variables

#属性用小写或者小写加上下划线命名的, most of the time, indicates the state of an object, which can be a noun or an adjective, which can also be a small phrase when needed, as follows

Class Coi (object):

_c=[]

Def v (self,a):

Self._c.append (a)

def _cc (self):

Return '. Join (Self._c)

Connect=property (_CC)

Aa=coi ()

AA.V (' TT ')

#类的名称问题是使用CamelCase格式命名, when the definition is a private class of modules, there may also be a leading underscore

#类和实例变量常常是名词短语, the use of logic is consistent with the verb phrase naming method, as follows

Class DS (object):

Def ope (self):

Pass

Class USER (object):

Pass

A=user ()

Db=ds ()

Db.ope ()

#模块和名

#除了特殊模块__init__之外, the module names are named with a lowercase letter that is not underlined, as follows

"""

Os,sys,shbutil

When the module is private to the package, a leading underscore is added, the C or C + + module name is usually underlined and imported into a pure Python module

Packages adhere to the same rules because they behave like modules in a namespace

"""

Python advanced Programming Selection Good name: Pepe8 and naming best practices

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.