Python advanced Programming Selection Good name: Naming guide

Source: Internet
Author: User

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

# # python:2.x

# __author__ = ' Administrator '

#命名指南

#一组常用的命名规则可以被应用到变量, method functions and properties, the names of classes and modules play an important role in namespaces, so there are generally 2 modes: sleep mode and anti-pattern

#使用has, the is prefix names a Boolean element, such as

#当一个元素用来保存布尔值, using the Has,is prefix to name a Boolean element is a good choice.

Class DB (object):

Is_connected=false

Has_cache=false

Has_1=db ()

Print Has_1.has_cache

#复数形式命名序列元素

#当一个元素是用来保存一个序列, it is a good idea to use plural names, and it is also possible to output mappings in a sequence-like format.

Class DN (object):

connected_user=[' Tarek ']

tables={' cutomer ': [' id ', ' frm ', ' lat ']}

#用显式全称命名字典

#当一个变量用来保存一个映射时, you should use an explicit name whenever possible

perespod_addre={' appl ', ' 65556 '}

#避免通用名称

#当在代码中不构建一个新的抽象数据类型 such names as list,dict,sequence are harmful, even for local variables, as follows

def comput (data):

For element in data:

Yield element*12

def disup_num (num):

For NUM1 in Num:

Pass

#避免现有名称, when the name already has a bad habit in context, it creates a lot of confusion during debugging

Def bad_ct ():

Os=1

Import PDB

Pdb.set_trace ()

Return os+2

#在这个例子中, the OS name will be obscured by the code and built-in from standard library module names should be avoided,

#尝试创建独特名称, even if they are local variables of the context, for keywords, add a suffix underline to avoid a conflict one method, as follows

def x (tree,or_=true):

Pass

#class are often changed to Klass or CLS, as follows

def funct (Klass,*a,**ki):

Return Klass (*a,**ki)

Print

#________

#参数最佳实践

#根据3个简单规则来说明前面的内容

"""

Building parameters based on iterative design

Trust parameters and tests

Be careful with the magic parameters *args and **kw

"""

#根据迭代设计构建参数

#当每个函数都有一个固定的, a well-designed list of parameters can be robust, but this cannot be done in the first version, so building parameters based on iteration design, they should reflect the usage scenario for creating the element, and evolve accordingly, as follows

#当附加一些参数时, you should have as many default values as possible to avoid any degradation

Class BD (object):

def _q (SELF,Q1,Q2):

print ' _q (2 parameters) '

def execute (SELF,Q1):

Self._q (Q1, ' execute ')

BD (). Execute (' my query ')

Import logging

Class BD (object):

def _q (Self,query,types,logger):

Logger (' song ')

def execute (self,a,loggeg=logging.info):

Self._q (A, ' execute ', logging)

#当一个公共元素的参数必须变化时, a deprecation process will be used, explained later

#信任参数和测试

#基于python动态类型特性考虑. Some developers use assertions in functions and methods to determine the correct content, as follows:

def division (D,D1):

Assert type (d) in (Long,int,float)

Assert type (D1) in (long,int,float)

Return D/D1

#这通常是那些习惯于动态类型并且感觉python中缺少点什么开发人员

#这种检查参数的方法是契约式设计编程风格 (design by Contract:http://en.wikipedia.org/wiki/design_by_contract), in such designs, The code checks the assertion before it actually runs

#主要2个问题

"""

1:dbc code explains how it should be used, resulting in reduced program legibility

2: May make code execution slower because each invocation is asserted

"""

"""

2 can be avoided by executing an interpreter with the-o option, in which case all assertions are deleted from the code before the trade city bytecode is created, so that the check is lost

In any case, assertions must be done with caution and should not cause Python to become a static type language, and the only use scenario is to protect the code from calls that are not meaningless.

A healthy test-driven development style will in most cases provide a robust base code, where functional and unit tests validate all the usage scenarios for which the code is created

When code in the library is used by external elements, it can be useful to build assertions because the input data can cause the program to end or even cause corruption, which is most likely to occur in the processing of a database or in file system code.

Another Lujiang is the fuzzy test (Fuzz testing:en.wikipedia.org/wiki/fuzz_testing), which detects its weaknesses by sending a random block of data to the program, and when a new flaw is found, the code can be repaired accordingly. and add a new test.

Let's focus on a code that follows the TDD approach, evolves in the right direction and adjusts whenever a new flaw arises, so that the robustness is getting better, and when it is done in the right way, the list of assertions in the test becomes somewhat similar to the predicted list.

DBC libraries, which can be found in contracts for Python (www.wayforward.net/pycontract/)

"""

#小心使用 *a,**k Magic parameters can break the robustness of functions or methods, use signatures to blur, and code often starts not to build small parametric parsers where they appear, as follows

def f (**k):

If ' d ' in K:

print ' Ok1 '

Else

print ' Ok2 '

print ' F (**k) is a dictionary '

#当参数列表很长而且很复杂时, it is tempting to add magical parameters, but this usually means that it is a fragile function or method that should be decomposed or reconstructed

#当 *a is used to handle a series of elements that are handled in the same way in a function, it is better to ask for a unique container parameter such as iterator, as follows

def s (*a1): #可行

T1=0

For a in A1:

T1+=a

return T1

def s (A1): #更好

T1=0

For a in A1:

T1+=a

return T1

#对于 **k, the same rules as 8a, which makes the method signature more meaningful

def kw (**kw): #可行

N=kw.get (' A ', ' B ')

Return '%s '% (n)

def kw (A= ' A ', b= ' B ', c= ' C '):

Return A,b,c

#另一种有趣的庐江是创建一个聚焦多个相关参数以提供执行环境容器类, this structure is different from 8a,**k because it can provide work on numeric values and be able to drill down into internal artifacts independently, using code as a parameter without having to deal with its internal build

#web例子

def log1 (reque): #版本1

Return Reque.get (' http ', ' no URL ')

def log2 (Re1): #版本2

Print re1.get (' http ', ' no Url1 ')

Print re1.get (' http ', ' no Url1 ')

#魔法参数有时候是无法避免的, especially in metaprogramming, in general, when it comes to only the unknowns in the function, the magic parameters are good, as follows:

def log (**conte):

Logging.info (str (conte))

#类名: It must be concise, precise, and sufficient to understand the work done by the class from the center, and one common method is to use a representation of its type or attribute suffix, such as:

"""

SQLEngine

Mimetypes

Stringwidget

TestCase

"""

#对于基类而言, you can use a base or abstract prefix, as follows

"""

Basecookie

Abstractformatter

"""

#最重要的是要和类特性保持五毒, such as:

#SMTP. Smtp_send () redundant information in namespace

#SMTP. Send () is more readable and easier to remember

#模块和名名称

#在模块和名名称中, should reflect the purpose of the content, these names should be short, use lowercase letters, do not use underscores, as follows

"""

Sqlite

Postgres

Shal

"""

#如果它们实现一个协议, the Lib prefix is usually used, as follows

Import Smtplib,urllib,telnetlib

#它们在命名空间中也必须保持一致, this will be easier to use, as follows

#from widgets.stringwidgets Import Textwidget Bad

#from widgets.strings import Textwidget okay.

#同样, you should always avoid using the same name as from the standard library module

#当一个模块变得比较复杂, when there are many classes, it is a good practice to create a package and divide the module elements into other modules.

#__init__模块也可以用来将一些API放回最高级别中, because it does not affect the use of these APIs, and helps to organize the code into smaller parts, such as a module in the Foo package, as follows

#from Module1 Import F1,f2

#from Mudule2 Import F3

#允许用户直接导入功能, as follows

# from Foo Import F1

# from Foo import f2,f3

# but be aware that this may increase the likelihood of cyclic dependencies, adding code in the __init__ module will be instantiated, so use caution.

Python advanced Programming Selection Good name: Naming guide

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.