《编写高质量代码 改善python程序的91个建议》第一章 引论 1-7

建议1: pythonic化,可读性;

建议2:起名具有自释性  代码检测建议标准pep8;

建议3:与C语言的区分,虽然其底层是C语言。披着狼皮的羊,看起来Ta就要像一只狼的样子!

             (1) ”缩进“代替”{ }“

             (2) " "和 ‘ ’  本身不严格区分

             (3)  X if  statence else Y   代替     statence ? X : Y

             (4)  代替 switch...case... : if ... elif...elif...else...

建议4:添加注释

            块注释    #xxxxxxx

            行注释
            """ Describe xxxxx   Args:  param1: xxx param2:xxx   Return: xxxx

            """

           文档注释: 

            

 

建议5:适当添加空行,增加可阅读性,
          (1)局部功能块完成后换行

          (2) 函数调用者在上, 被调用者在下

          (3)每行不超过80字符,分行要对齐

          (4)合理使用空格

建议6:考虑向下兼容,函数只做一件事

建议7:存在一小部分常量 True False None   

          (1)大写变量名只是形式上的常量;

          (2)定义常量类

class _const:
        class ConstError(TypeError): pass
        class ConstCaseError(ConstError): pass

        def __setattr__(self, name, value):
            if self.__dict__.has_key(name):
                raise self.ConstError, "Can't change const. %s" % name
            if not namel.isupper():
                raise self.ConstCaseError, 'name "%s" is not upper' % name
            self.__dict__[name] = value

import sys
sys.modules[__name__] = _const()
import const 
const.MY_CONSTANT = 1
const.MY_SECOND_CONSTANT = 2
const.MY_THIRD_CONSTANT = 'a'

应用:
from constant import const
print(const.MY_CONSTANT)
print(const.MY_THIRD_CONSTANT+1)

 

  

posted @ 2019-11-28 11:45  一花一世界V5  阅读(157)  评论(0编辑  收藏  举报