小猿圈之Python开发的技巧一?

python现在成为主流的开发语言,越来越多的朋友开始学习python,其实学习python有很多的学习技巧,今天小猿圈老师带你了解一下:python学习技巧,让你们可以简单快速掌握python,下面咱们开始我们的python之旅吧!

显示有限的接口到外部:

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

#!/usr/bin/envpython

#-*-coding:utf-8-*-

from base import  APIBase

from client import Client

from  decorator  import interface,export,stream

from server import Server

from storage  import Storage

from util import(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被过滤掉

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

#输出结果

[1,3,5]

一行作判断:

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

lst=[1,2,3]

new_lst=lst[0]iflstisnotNoneelseNone

print new_lst

#打印结果

1

装饰器之单例:

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

#单例装饰器

def singleton(cls):

instances=dict()#初始为空

def_singleton(*args,**kwargs):

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

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,想要了解更多内容的小伙伴可以到小猿圈学习更多的技巧,想要学好Python的朋友加油吧。

猜你喜欢

转载自blog.csdn.net/qq_42210792/article/details/91366175