python阅读代码有助于养成优秀的代码风格

来源:千锋教育
发布时间:2023-11-07 02:35:39
分享

“优秀的代码不需要文档”,这句话虽然说的有些夸张的成份,但是也并无一定道理。优秀的项目中的代码,注释占的比重是相当大的。比方tornado框架中的代码:

classHTTPServer(TCPServer,Configurable,

httputil.HTTPServerConnectionDelegate):

r"""Anon-blocking,single-threadedHTTPserver.

Aserverisdefinedbyasubclassof.HTTPServerConnectionDelegate,

or,forbackwardscompatibility,acallbackthattakesan

.HTTPServerRequestasanargument.Thedelegateisusuallya

tornado.web.Application.

HTTPServersupportskeep-aliveconnectionsbydefault

(automaticallyforHTTP/1.1,orforHTTP/1.0whentheclient

requestsConnection:keep-alive).

IfxheadersisTrue,wesupportthe

X-Real-Ip/X-Forwarded-Forand

X-Scheme/X-Forwarded-Protoheaders,whichoverridethe

remoteIPandURIscheme/protocolforallrequests.Theseheaders

areusefulwhenrunningTornadobehindareverseproxyorload

balancer.Theprotocolargumentcanalsobesettohttps

ifTornadoisrunbehindanSSL-decodingproxythatdoesnotsetoneof

thesupportedxheaders.

TomakethisserverserveSSLtraffic,sendthessl_optionskeyword

argumentwithanssl.SSLContextobject.Forcompatibilitywitholder

versionsofPythonssl_optionsmayalsobeadictionaryofkeyword

argumentsforthessl.wrap_socketmethod.::

ssl_ctx=ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)

ssl_ctx.load_cert_chain(os.path.join(data_dir,"mydomain.crt"),

os.path.join(data_dir,"mydomain.key"))

HTTPServer(applicaton,ssl_options=ssl_ctx)

HTTPServerinitializationfollowsoneofthreepatterns(the

initializationmethodsaredefinedontornado.tcpserver.TCPServer):

1.~tornado.tcpserver.TCPServer.listen:simplesingle-process::

server=HTTPServer(app)

server.listen(8888)

IOLoop.current().start()

Inmanycases,tornado.web.Application.listencanbeusedtoavoid

theneedtoexplicitlycreatetheHTTPServer.

2.~tornado.tcpserver.TCPServer.bind/~tornado.tcpserver.TCPServer.start:

simplemulti-process::

server=HTTPServer(app)

server.bind(8888)

server.start(0)#Forksmultiplesub-processes

IOLoop.current().start()

Whenusingthisinterface,an.IOLoopmust*not*bepassed

totheHTTPServerconstructor.~.TCPServer.startwillalwaysstart

theserveronthedefaultsingleton.IOLoop.

3.~tornado.tcpserver.TCPServer.add_sockets:advancedmulti-process::

sockets=tornado.netutil.bind_sockets(8888)

tornado.process.fork_processes(0)

server=HTTPServer(app)

server.add_sockets(sockets)

IOLoop.current().start()

The~.TCPServer.add_socketsinterfaceismorecomplicated,

butitcanbeusedwithtornado.process.fork_processesto

giveyoumoreflexibilityinwhentheforkhappens.

~.TCPServer.add_socketscanalsobeusedinsingle-process

serversifyouwanttocreateyourlisteningsocketsinsome

wayotherthantornado.netutil.bind_sockets.

..versionchanged::4.0

Addeddecompress_request,chunk_size,max_header_size,

idle_connection_timeout,body_timeout,max_body_size

arguments.Addedsupportfor.HTTPServerConnectionDelegate

instancesasrequest_callback.

..versionchanged::4.1

.HTTPServerConnectionDelegate.start_requestisnowcalledwith

twoarguments(server_conn,request_conn)(inaccordancewiththe

documentation)insteadofone(request_conn).

..versionchanged::4.2

HTTPServerisnowasubclassoftornado.util.Configurable.

"""

def__init__(self,*args,**kwargs):

#Ignoreargsto__init__;realinitializationbelongsin

#initializesincewe'reConfigurable.(there'ssomething

#weirdininitializationorderbetweenthisclass,

#Configurable,andTCPServersowecan'tleave__init__out

#completely)

pass

上面的注释包含了:类的说明、例子、版本主要改动。

优秀的代码风格:看到名字就能知道它是用来干什么的(顾名思义)、结构清晰、代码风格统一(命名规则、格式)

这些优秀的特质都是为了:可读性、容易理解。正如:代码主要是给人看的,让计算机运行是次要的

如果是在阅读了不好的代码,如果你心里在骂:“这代码简直是一坨

所以,自己的优秀的编码风格也是成为一个合格的程序员必备的一项技能(面试要求会有这一项),通过阅读代码学习,模仿优秀的代码风格,有助于自己写出‘漂亮’、整洁的代码。

以上内容为大家介绍了python阅读代码有助于养成优秀的代码风格,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

声明:本站部分稿件版权来源于网络,如有侵犯版权,请及时联系我们。

相关推荐

  • Python 条件对象 条件对象总是与某种类型的锁对象相关联,锁对象可以通过传入获得,或者在缺省的情况下自动创建。threading.Condition(lock=None)实现条件对象的类。它具有如下方法:acquire(
  • Python 信号量对象 和锁机制一样,信号量机制也是一种实现线程同步的机制,不过它比锁多了一个计数器,这个计数器主要用来计算当前剩余的锁的数量。threading.Semaphore(value=1)信号量实现类,可选参数v
  • Python 事件对象 一个线程发出事件信号,其他线程等待该信号,这是最简单的线程之间通信机制之一。threading.Event实现事件对象的类。它有如下方法:is_set():当内部标志为True时返回True。set(
  • Python 解释器的作用 python解释器的主要作用是将我们在.py文件中写好的代码交给机器去执行,比较常见的解释器包括如下几种:CPython:官方解释器,我们从官网下载安装后获得的就是这个解释器,它使用C语言开发,是使用
  • Python 领域模型 python需求分析阶段不区分面向对象还是面向过程领域模型是完成从需求分析到面向对象设计的一座桥梁领域模型定义:领域模型是对领域内的概念或现实世界中对象的可视化表示,又称为观念模型,领域对象模型,分析
  • Python 图的功能 综述UML是数据库设计过程中,在E-R图(实体-联系图)的设计后的进一步建模。要了解一下UML设计中有的图例及基本作用。首先对UML中的各个图的功用做一个简单介绍:用例图描述角色以及角色与用例之间的连