最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx

上传人:b****6 文档编号:12808276 上传时间:2023-06-08 格式:DOCX 页数:14 大小:146.69KB
下载 相关 举报
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第1页
第1页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第2页
第2页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第3页
第3页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第4页
第4页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第5页
第5页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第6页
第6页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第7页
第7页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第8页
第8页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第9页
第9页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第10页
第10页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第11页
第11页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第12页
第12页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第13页
第13页 / 共14页
最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx_第14页
第14页 / 共14页
亲,该文档总共14页,全部预览完了,如果喜欢就下载吧!
下载资源
资源描述

最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx

《最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx》由会员分享,可在线阅读,更多相关《最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx(14页珍藏版)》请在冰点文库上搜索。

最流行的编程入门语言Python语句函数与方法的使用技巧总结.docx

最流行的编程入门语言Python语句函数与方法的使用技巧总结

Python语句、函数与方法的使用技巧总结

 

显示有限的接口到外部

当发布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']

with的魔力

with语句需要支持上下文管理协议的对象,上下文管理协议包含__enter__和__exit__两个方法。

with语句建立运行时上下文需要通过这两个方法执行进入和退出操作。

其中上下文表达式是跟在with之后的表达式,该表达式返回一个上下文管理对象。

#常见with使用场景

withopen("test.txt","r")asmy_file:

#注意,是__enter__()方法的返回值赋值给了my_file,

forlineinmy_file:

printline

知道具体原理,我们可以自定义支持上下文管理协议的类,类中实现__enter__和__exit__方法。

#!

/usr/bin/envpython

#-*-coding:

utf-8-*-

classMyWith(object):

def__init__(self):

print"__init__method"

def__enter__(self):

print"__enter__method"

returnself#返回对象给as后的变量

def__exit__(self,exc_type,exc_value,exc_traceback):

print"__exit__method"

ifexc_tracebackisNone:

print"ExitedwithoutException"

returnTrue

else:

print"ExitedwithException"

returnFalse

deftest_with():

withMyWith()asmy_with:

print"runningmy_with"

print"------分割线-----"

withMyWith()asmy_with:

print"runningbeforeException"

raiseException

print"runningafterException"

if__name__=='__main__':

test_with()

执行结果如下:

__init__method

__enter__method

runningmy_with

__exit__method

ExitedwithoutException

------分割线-----

__init__method

__enter__method

runningbeforeException

__exit__method

ExitedwithException

Traceback(mostrecentcalllast):

File"bin/python",line34,in

exec(compile(__file__f.read(),__file__,"exec"))

File"test_with.py",line33,in

test_with()

File"test_with.py",line28,intest_with

raiseException

Exception

证明了会先执行__enter__方法,然后调用with内的逻辑,最后执行__exit__做退出处理,并且,即使出现异常也能正常退出

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

staticmethod装饰器

类中两种常用的装饰,首先区分一下他们:

普通成员函数,其中第一个隐式参数为对象

classmethod装饰器,类方法(给人感觉非常类似于OC中的类方法),其中第一个隐式参数为类

staticmethod装饰器,没有任何隐式参数.python中的静态方法类似与C++中的静态方法

#!

/usr/bin/envpython

#-*-coding:

utf-8-*-

classA(object):

#普通成员函数

deffoo(self,x):

print"executingfoo(%s,%s)"%(self,x)

@classmethod#使用classmethod进行装饰

defclass_foo(cls,x):

print"executingclass_foo(%s,%s)"%(cls,x)

@staticmethod#使用staticmethod进行装饰

defstatic_foo(x):

print"executingstatic_foo(%s)"%x

deftest_three_method():

obj=A()

#直接调用噗通的成员方法

obj.foo("para")#此处obj对象作为成员函数的隐式参数,就是self

obj.class_foo("para")#此处类作为隐式参数被传入,就是cls

A.class_foo("para")#更直接的类方法调用

obj.static_foo("para")#静态方法并没有任何隐式参数,但是要通过对象或者类进行调用

A.static_foo("para")

if__name__=='__main__':

test_three_method()

#函数输出

executingfoo(<__main__.Aobjectat0x100ba4e10>,para)

executingclass_foo(,para)

executingclass_foo(,para)

executingstatic_foo(para)

executingstatic_foo(para)

property装饰器

定义私有类属性

将property与装饰器结合实现属性私有化(更简单安全的实现get和set方法)。

#python内建函数

property(fget=None,fset=None,fdel=None,doc=None)

fget是获取属性的值的函数,fset是设置属性值的函数,fdel是删除属性的函数,doc是一个字符串(_像注释一样)。

从实现来看,这些参数都是可选的。

property有三个方法getter(),setter()和delete()来指定fget,fset和fdel。

这表示以下这行:

classStudent(object):

@property#相当于property.getter(score)或者property(score)

defscore(self):

returnself._score

@score.setter#相当于score=property.setter(score)

defscore(self,value):

ifnotisinstance(value,int):

raiseValueError('scoremustbeaninteger!

')

ifvalue<0orvalue>100:

raiseValueError('scoremustbetween0~100!

')

self._score=value

iter魔法

通过yield和__iter__的结合,我们可以把一个对象变成可迭代的

通过__str__的重写,可以直接通过想要的形式打印对象

#!

/usr/bin/envpython

#-*-coding:

utf-8-*-

classTestIter(object):

def__init__(self):

self.lst=[1,2,3,4,5]

defread(self):

foreleinxrange(len(self.lst)):

yieldele

def__iter__(self):

returnself.read()

def__str__(self):

return','.join(map(str,self.lst))

__repr__=__str__

deftest_iter():

obj=TestIter()

fornuminobj:

printnum

printobj

if__name__=='__main__':

test_iter()

神奇partial

partial使用上很像C++中仿函数(函数对象)。

在stackoverflow给出了类似与partial的运行方式:

defpartial(func,*part_args):

defwrapper(*extra_args):

args=list(part_args)

args.extend(extra_args)

returnfunc(*args)

returnwrapper

利用用闭包的特性绑定预先绑定一些函数参数,返回一个可调用的变量,直到真正的调用执行:

#!

/usr/bin/envpython

#-*-coding:

utf-8-*-

fromfunctoolsimportpartial

defsum(a,b):

returna+b

deftest_partial():

fun=partial(sum,2)#事先绑定一个参数,fun成为一个只需要一个参数的可调用变量

printfun(3)#实现执行的即是sum(2,3)

if__name__=='__main__':

test_partial()

#执行结果

5

神秘eval

eval我理解为一种内嵌的python解释器(这种解释可能会有偏差),会解释字符串为对应的代码并执行,并且将执行结果返回。

看一下下面这个例子:

#!

/usr/bin/envpython

#-*-coding:

utf-8-*-

deftest_first():

return3

deftest_second(num):

returnnum

action={#可以看做是一个sandbox

"para":

5,

"test_first":

test_first,

"test_second":

test_second

}

deftest_eavl():

condition="para==5andtest_second(test_first)>5"

res=eval(condition,action)#解释condition并根据action对应的动作执行

printres

if__name__=='_

exec

exec在Python中会忽略返回值,总是返回None,eval会返回执行代码或语句的返回值

exec和eval在执行代码时,除了返回值其他行为都相同

在传入字符串时,会使用compile(source,'',mode)编译字节码。

mode的取值为exec和eval

#!

/usr/bin/envpython

#-*-coding:

utf-8-*-

deftest_first():

print"hello"

deftest_second():

test_first()

print"second"

deftest_third():

print"third"

action={

"test_second":

test_second,

"test_third":

test_third

}

deftest_exec():

exec"test_second"inaction

if__name__=='__main__':

test_exec()#无法看到执行结果

getattr

getattr(object,name[,default])返回对象的命名属性,属性名必须是字符串。

如果字符串是对象的属性名之一,结果就是该属性的值。

例如,getattr(x,‘foobar')_等价于x.foobar。

如果属性名不存在,如果有默认值则返回默认值,否则触发AttributeError。

#使用范例

classTestGetAttr(object):

test="testattribute"

defsay(self):

print"testmethod"

deftest_getattr():

my_test=TestGetAttr()

try:

printgetattr(my_test,"test")

exceptAttributeError:

print"AttributeError!

"

try:

getattr(my_test,"say")()

exceptAttributeError:

#没有该属性,且没有指定返回值的情况下

print"MethodError!

"

if__name__=='__main__':

test_getattr()

#输出结果

testattribute

testmethod

命令行处理

defprocess_command_line(argv):

"""

Returna2-tuple:

(settingsobject,argslist).

`argv`isalistofarguments,or`None`for``sys.argv[1:

]``.

"""

ifargvisNone:

argv=sys.argv[1:

]

#initializetheparserobject:

parser=optparse.OptionParser(

formatter=optparse.TitledHelpFormatter(width=78),

add_help_option=None)

#defineoptionshere:

parser.add_option(#customizeddescription;put--helplast

'-h','--help',action='help',

help='Showthishelpmessageandexit.')

settings,args=parser.parse_args(argv)

#checknumberofarguments,verifyvalues,etc.:

ifargs:

parser.error('programtakesnocommand-linearguments;'

'"%s"ignored.'%(args,))

#furtherprocesssettings&argsifnecessary

returnsettings,args

defmain(argv=None):

settings,args=process_command_line(argv)

#applicationcodehere,like:

#run(settings,args)

return0#success

if__name__=='__main__':

status=main()

sys.exit(status)

读写csv文件

#从csv中读取文件,基本和传统文件读取类似

importcsv

withopen('data.csv','rb')asf:

reader=csv.reader(f)

forrowinreader:

printrow

#向csv文件写入

importcsv

withopen('data.csv','wb')asf:

writer=csv.writer(f)

writer.writerow(['name','address','age'])#单行写入

data=[

('xiaoming','china','10'),

('Lily','USA','12')]

writer.writerows(data)#多行写入

各种时间形式转换

只发一张网上的图,然后查文档就好了,这个是记不住的

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 自然科学 > 物理

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2