小猿圈解析Python开发的技巧都有哪些?

现在人工智能越来越实用,甚至深入到千家万户,随之而来的就是python技术的火爆,今天小猿圈python讲师为你讲解一下python开发的技巧都有哪些?希望对于刚刚自学python的你有一定的帮助。
小猿圈提供的热门开发课程有JavaEE+分布式开发、全栈HTML5+、Python人工智能、Linux等。官网网址:https://www.apeland.cn/
显示有限的接口到外部:

当发布python第三方package时,并不希望代码中所有的函数或者class可以被外部import,在__init__.py中添加__all__属性,该list中填写可以import的类或者函数名,可以起到限制的import的作用,防止外部import其他函数或者类。

#!/usr/bin/envpython

#--coding:utf-8--

frombaseimportAPIBase

fromclientimportClient

fromdecoratorimportinterface,export,stream

fromserverimportServer

fromstorageimportStorage

fromutilimport(LogFormatter,disable_logging_to_stderr,

enable_logging_to_kids,info)

all=[‘APIBase’,‘Client’,‘LogFormatter’,‘Server’,

‘Storage’,‘disable_logging_to_stderr’,‘enable_logging_to_kids’,

‘export’,‘info’,‘interface’,‘stream’]

filter的用法:

相对filter而言,map和reduce使用的会更频繁一些,filter正如其名字,按照某种规则过滤掉一些元素。

#!/usr/bin/envpython

#--coding:utf-8--

lst=[1,2,3,4,5,6]

#所有奇数都会返回True,偶数会返回False被过滤掉

printfilter(lambdax:x%2!=0,lst)

#输出结果

[1,3,5]

一行作判断:

当条件满足时,返回的为等号后面的变量,否则返回else后语句。

lst=[1,2,3]

new_lst=lst[0]iflstisnotNoneelseNone

printnew_lst

#打印结果

1

装饰器之单例:

使用装饰器实现简单的单例模式

#单例装饰器

defsingleton(cls):

instances=dict()#初始为空

def_singleton(*args,**kwargs):

ifclsnotininstances:#如果不存在,则创建并放入字典

instances[cls]=cls(*args,**kwargs)

returninstances[cls]

return_singleton

@singleton

classTest(object):

pass

if__name__==‘main’:

t1=Test()

t2=Test()

#两者具有相同的地址

printt1,t2

以上就是小猿圈python讲师给大家分享的Python开发的技巧,希望对小伙伴们有所帮助,想要了解更多内容的小伙伴可以到小猿圈直接观看python自学交流群:242719133,想要学好Python开发技术的小伙伴快快行动吧。

猜你喜欢

转载自blog.csdn.net/coding567/article/details/89473426