扣丁学堂分享Python干货 浅谈Python开发的技巧

2018-07-24 14:22:20 409浏览

今天扣丁学堂Python培训小编给大家分享一篇Python干货的文章,文章主要是讲解Python开发的技巧,对Python感兴趣或者是喜欢Python的小伙伴就随小编一起来了解一下Python开发的技巧吧。



扣丁学堂分享Python干货 浅谈Python开发的技巧



显示有限的接口到外部:


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


#!/usr/bin/env python

# -*- 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/env python

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

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

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

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

#输出结果

[1, 3, 5]


一行作判断:


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


lst = [1, 2, 3]

new_lst = lst[0] if lst is not None else None

print new_lst

# 打印结果

1


装饰器之单例:


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


# 单例装饰器

def singleton(cls):

instances = dict() # 初始为空

def _singleton(*args, **kwargs):

if cls not in instances: #如果不存在, 则创建并放入字典

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

return instances[cls]

return _singleton

@singleton

class Test(object):

pass

if __name__ == '__main__':

t1 = Test()

t2 = Test()

# 两者具有相同的地址

print t1, t2


以上就是扣丁学堂Python在线学习小编给大家分享的Python开发的技巧,希望对小伙伴们有所帮助,想要了解更多内容的小伙伴可以登录扣丁学堂官网咨询。想要学好Python开发小编给大家推荐口碑良好的扣丁学堂,扣丁学堂有专业老师制定的Python学习路线图辅助学员学习,此外还有与时俱进的Python课程体系和大量的Python视频教程供学员观看学习,想要学好Python开发技术的小伙伴快快行动吧。扣丁学堂Python技术交流群:279521237。


扣丁学堂微信公众号

关注微信公众号获取更多学习资料



查看更多关于"Python开发资讯"的相关文章>


标签: 扣丁学堂Python培训 Python干货 Python开发的技巧 Python培训 Python视频教程 Python基础教程 python安装教程 Python核心编程 Python在线教程 Python在线视频 Python在线学习

热门专区

暂无热门资讯

课程推荐

微信
微博
15311698296

全国免费咨询热线

邮箱:codingke@1000phone.com

官方群:148715490

北京千锋互联科技有限公司版权所有   北京市海淀区宝盛北里西区28号中关村智诚科创大厦4层
京ICP备12003911号-6   Copyright © 2013 - 2019

京公网安备 11010802030908号