导航:首页 > 编程语言 > 装饰器模式python

装饰器模式python

发布时间:2022-09-18 15:42:36

‘壹’ 请教python 使用装饰器实现单例模式的原理

简单来讲,可以不严谨地把Python的装饰器看做一个包装函数的函数。 比如,有一个函数: def func(): print 'func() run.' if '__main__' == __name__: func() 运行后将输出: func() run. 现在需要在函数运行前后打印一条日志

‘贰’ Python有哪些技术上的优点比其他语言好在哪儿

Python有哪些技术上的优点


1. 面向对象和函数式

从根本上讲,Python是一种面向对象的语言。它的类模型支持多态、运算符重载和多重继承等高级概念,并且以Python特有的简洁的语法和类型为背景,OOP十分易于使用。事实上,即使你不懂这些术语,仍会发现学习Python比学习其他OOP语言要容易得多。

除了作为一种强大的代码组织和重用手段以外,Python的OOP本质使它成为其他面向对象系统语言的理想脚本工具。例如,通过适当的粘接代码,Python程序可以对C++、Java和C#的类进行子类的定制。

OOP只是Python的一个选择而已,这一点非常重要。即使不能立马成为一个面向对象高手,但你同样可以继续深入学习。就像C++一样,Python既支持面向对象编程也支持面向过程编程的模式。如果条件允许,其面向对象的工具可以立即派上用场。这对策略开发模式十分有用,该模式常用于软件开发的设计阶段。

除了最初的过程式(语句为基础)和面向对象(类为基础)的编程范式,Python在最近几年内置了对函数式编程的支持——一个多数情况下包括生成器、推导、闭包、映射、装饰器、匿名lambda函数和第一类函数对象的集合。这是对其本身OOP工具的补充和替代。

2. 免费

Python的使用和分发是完全免费的。就像其他的开源软件一样,例如,Tcl、Perl、Linux和Apache。你可以从Internet上免费获得Python的源代码。你可以不受限制地复制Python,或将其嵌入你的系统或者随产品一起发布。实际上,如果你愿意的话,甚至可以销售它的源代码。

但请别误会:“免费”并不代表“没有支持”。恰恰相反,Python的在线社区对用户需求的响应和商业软件一样快。而且,由于Python完全开放源代码,提高了开发者的实力,并产生了一个很大的专家团队。

尽管研究或改变一种程序语言的实现并不是对每一个人来说都那么有趣,但是当你知道如果需要的话可以做到这些,该是多么的令人欣慰。你不需要去依赖商业厂商的智慧,因为最终的文档和终极的净土(源码)任凭你的使用。

Python的开发是由社区驱动的,是Internet大范围的协同合作努力的结果。Python语言的改变必须遵循一套规范而有约束力的程序(称作PEP流程),并需要经过规范的测试系统进行彻底检查。正是这样才使得Python相对于其他语言和系统可以保守地持续改进。

尽管Python 2.X和Python 3.X版本之间的分裂有力并蓄意地破坏了这项传统,但通常它仍然体现在Python的这两个系列内部。

‘叁’ 如何理解Python装饰器

理解Python中的装饰器
@makebold
@makeitalic
def say():
return "Hello"

打印出如下的输出:
<b><i>Hello<i></b>

你会怎么做?最后给出的答案是:

def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped

def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped

@makebold
@makeitalic
def hello():
return "hello world"

print hello() ## 返回 <b><i>hello world</i></b>

现在我们来看看如何从一些最基础的方式来理解Python的装饰器。英文讨论参考Here。
装饰器是一个很着名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。
1.1. 需求是怎么来的?
装饰器的定义很是抽象,我们来看一个小例子。

def foo():
print 'in foo()'
foo()

这是一个很无聊的函数没错。但是突然有一个更无聊的人,我们称呼他为B君,说我想看看执行这个函数用了多长时间,好吧,那么我们可以这样做:

import time
def foo():
start = time.clock()
print 'in foo()'
end = time.clock()
print 'used:', end - start

foo()

很好,功能看起来无懈可击。可是蛋疼的B君此刻突然不想看这个函数了,他对另一个叫foo2的函数产生了更浓厚的兴趣。
怎么办呢?如果把以上新增加的代码复制到foo2里,这就犯了大忌了~复制什么的难道不是最讨厌了么!而且,如果B君继续看了其他的函数呢?
1.2. 以不变应万变,是变也
还记得吗,函数在Python中是一等公民,那么我们可以考虑重新定义一个函数timeit,将foo的引用传递给他,然后在timeit中调用foo并进行计时,这样,我们就达到了不改动foo定义的目的,而且,不论B君看了多少个函数,我们都不用去修改函数定义了!

import time

def foo():
print 'in foo()'

def timeit(func):
start = time.clock()
func()
end =time.clock()
print 'used:', end - start

timeit(foo)

看起来逻辑上并没有问题,一切都很美好并且运作正常!……等等,我们似乎修改了调用部分的代码。原本我们是这样调用的:foo(),修改以后变成了:timeit(foo)。这样的话,如果foo在N处都被调用了,你就不得不去修改这N处的代码。或者更极端的,考虑其中某处调用的代码无法修改这个情况,比如:这个函数是你交给别人使用的。
1.3. 最大限度地少改动!
既然如此,我们就来想想办法不修改调用的代码;如果不修改调用代码,也就意味着调用foo()需要产生调用timeit(foo)的效果。我们可以想到将timeit赋值给foo,但是timeit似乎带有一个参数……想办法把参数统一吧!如果timeit(foo)不是直接产生调用效果,而是返回一个与foo参数列表一致的函数的话……就很好办了,将timeit(foo)的返回值赋值给foo,然后,调用foo()的代码完全不用修改!

#-*- coding: UTF-8 -*-
import time

def foo():
print 'in foo()'

# 定义一个计时器,传入一个,并返回另一个附加了计时功能的方法
def timeit(func):

# 定义一个内嵌的包装函数,给传入的函数加上计时功能的包装
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start

# 将包装后的函数返回
return wrapper

foo = timeit(foo)
foo()

这样,一个简易的计时器就做好了!我们只需要在定义foo以后调用foo之前,加上foo = timeit(foo),就可以达到计时的目的,这也就是装饰器的概念,看起来像是foo被timeit装饰了。在在这个例子中,函数进入和退出时需要计时,这被称为一个横切面(Aspect),这种编程方式被称为面向切面的编程(Aspect-Oriented Programming)。与传统编程习惯的从上往下执行方式相比较而言,像是在函数执行的流程中横向地插入了一段逻辑。在特定的业务领域里,能减少大量重复代码。面向切面编程还有相当多的术语,这里就不多做介绍,感兴趣的话可以去找找相关的资料。
这个例子仅用于演示,并没有考虑foo带有参数和有返回值的情况,完善它的重任就交给你了 :)
上面这段代码看起来似乎已经不能再精简了,Python于是提供了一个语法糖来降低字符输入量。

import time

def timeit(func):
def wrapper():
start = time.clock()
func()
end =time.clock()
print 'used:', end - start
return wrapper

@timeit
def foo():
print 'in foo()'

foo()

重点关注第11行的@timeit,在定义上加上这一行与另外写foo = timeit(foo)完全等价,千万不要以为@有另外的魔力。除了字符输入少了一些,还有一个额外的好处:这样看上去更有装饰器的感觉。
-------------------
要理解python的装饰器,我们首先必须明白在Python中函数也是被视为对象。这一点很重要。先看一个例子:

def shout(word="yes") :
return word.capitalize()+" !"

print shout()
# 输出 : 'Yes !'

# 作为一个对象,你可以把函数赋给任何其他对象变量

scream = shout

# 注意我们没有使用圆括号,因为我们不是在调用函数
# 我们把函数shout赋给scream,也就是说你可以通过scream调用shout

print scream()
# 输出 : 'Yes !'

# 还有,你可以删除旧的名字shout,但是你仍然可以通过scream来访问该函数

del shout
try :
print shout()
except NameError, e :
print e
#输出 : "name 'shout' is not defined"

print scream()
# 输出 : 'Yes !'

我们暂且把这个话题放旁边,我们先看看python另外一个很有意思的属性:可以在函数中定义函数:

def talk() :

# 你可以在talk中定义另外一个函数
def whisper(word="yes") :
return word.lower()+"...";

# ... 并且立马使用它

print whisper()

# 你每次调用'talk',定义在talk里面的whisper同样也会被调用
talk()
# 输出 :
# yes...

# 但是"whisper" 不会单独存在:

try :
print whisper()
except NameError, e :
print e
#输出 : "name 'whisper' is not defined"*

函数引用
从以上两个例子我们可以得出,函数既然作为一个对象,因此:
1. 其可以被赋给其他变量
2. 其可以被定义在另外一个函数内
这也就是说,函数可以返回一个函数,看下面的例子:

def getTalk(type="shout") :

# 我们定义另外一个函数
def shout(word="yes") :
return word.capitalize()+" !"

def whisper(word="yes") :
return word.lower()+"...";

# 然后我们返回其中一个
if type == "shout" :
# 我们没有使用(),因为我们不是在调用该函数
# 我们是在返回该函数
return shout
else :
return whisper

# 然后怎么使用呢 ?

# 把该函数赋予某个变量
talk = getTalk()

# 这里你可以看到talk其实是一个函数对象:
print talk
#输出 : <function shout at 0xb7ea817c>

# 该对象由函数返回的其中一个对象:
print talk()

# 或者你可以直接如下调用 :
print getTalk("whisper")()
#输出 : yes...

还有,既然可以返回一个函数,我们可以把它作为参数传递给函数:

def doSomethingBefore(func) :
print "I do something before then I call the function you gave me"
print func()

doSomethingBefore(scream)
#输出 :
#I do something before then I call the function you gave me
#Yes !

这里你已经足够能理解装饰器了,其他它可被视为封装器。也就是说,它能够让你在装饰前后执行代码而无须改变函数本身内容。
手工装饰
那么如何进行手动装饰呢?

# 装饰器是一个函数,而其参数为另外一个函数
def my_shiny_new_decorator(a_function_to_decorate) :

# 在内部定义了另外一个函数:一个封装器。
# 这个函数将原始函数进行封装,所以你可以在它之前或者之后执行一些代码
def the_wrapper_around_the_original_function() :

# 放一些你希望在真正函数执行前的一些代码
print "Before the function runs"

# 执行原始函数
a_function_to_decorate()

# 放一些你希望在原始函数执行后的一些代码
print "After the function runs"

#在此刻,"a_function_to_decrorate"还没有被执行,我们返回了创建的封装函数
#封装器包含了函数以及其前后执行的代码,其已经准备完毕
return the_wrapper_around_the_original_function

# 现在想象下,你创建了一个你永远也不远再次接触的函数
def a_stand_alone_function() :
print "I am a stand alone function, don't you dare modify me"

a_stand_alone_function()
#输出: I am a stand alone function, don't you dare modify me

# 好了,你可以封装它实现行为的扩展。可以简单的把它丢给装饰器
# 装饰器将动态地把它和你要的代码封装起来,并且返回一个新的可用的函数。
a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
#输出 :
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs

现在你也许要求当每次调用a_stand_alone_function时,实际调用却是a_stand_alone_function_decorated。实现也很简单,可以用my_shiny_new_decorator来给a_stand_alone_function重新赋值。

a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
#输出 :
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs

# And guess what, that's EXACTLY what decorators do !

装饰器揭秘
前面的例子,我们可以使用装饰器的语法:

@my_shiny_new_decorator
def another_stand_alone_function() :
print "Leave me alone"

another_stand_alone_function()
#输出 :
#Before the function runs
#Leave me alone
#After the function runs

当然你也可以累积装饰:

def bread(func) :
def wrapper() :
print "</''''''\>"
func()
print "<\______/>"
return wrapper

def ingredients(func) :
def wrapper() :
print "#tomatoes#"
func()
print "~salad~"
return wrapper

def sandwich(food="--ham--") :
print food

sandwich()
#输出 : --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
#outputs :
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>

使用python装饰器语法:

@bread
@ingredients
def sandwich(food="--ham--") :
print food

sandwich()
#输出 :
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>

‘肆’ Python如果一个父类已经实例化了,现在想新建一个子类,给父类的这一个实例添加两个属性,如何实现

class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
class worker(People):
def __init__(self,name,age,salary):
super(worker,self).__init__(name,age)
self.salary = salary
tom = People("Tom", 22)
print type(tom).__name__
#not a safe way, but no new object
tom.__class__=worker
print type(tom).__name__
tom.salary = 250
print tom.salary
#safe way, but create a new object
workerTom = worker("Tom", 22, 200)
tom.__dict__ = workerTom.__dict__
print type(tom).__name__
print tom.salary

‘伍’ Python有设计模式么

Python设计模式主要分为三大类:创建型模式、结构型模式、行为型模式;三 大类中又被细分为23种设计模式,以下这几种是最常见的。
单例模式:是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个是实例时,单例对象就能派上用场。单例对象的要点有三个:一是某个类只能有一个实例;二是它必须自行创建整个实例,三是它必须自行向整个系统提供这个实例。
工厂模式:提供一个创建对象的接口,不像客户端暴露创建对象的过程,使用一个公共的接口来创建对象,可以分为三种:简单工厂、工厂方法、抽象工厂。一个类的行为或其算法可以在运行时更改,这种类型的设计模式属于行为型模式。
策略模式:是常见的设计模式之一,它是指对一系列的算法定义,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。换句话来讲,就是针对一个问题而定义出一个解决的模板,这个模板就是具体的策略,每个策略都是按照这个模板进行的,这种情况下我们有新的策略时就可以直接按照模板来写,而不会影响之前已经定义好的策略。
门面模式:门面模式也被称作外观模式。定义如下:要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行。门面模式提供一个高层次的接口,使得子系统更易于使用。门面模式注重统一的对象,也就是提供一个访问子系统的接口。门面模式与模板模式有相似的地方,都是对一些需要重复方法的封装。但本质上是不同的,模板模式是对类本身的方法的封装,其被封装的方法也可以单独使用;门面模式,是对子系统的封装,其被封装的接口理论上是不会被单独提出来使用的。

‘陆’ Python中装饰器为什么只是第一次执行被装饰函数的时候才调用

可以的啦#-*-coding:UTF-8-*-fromfunctoolsimportwraps__author__='lpe234'defsingleton(cls):"""装饰器实现单例模式:paramcls::return:"""instances={}@wraps(cls)def_singleton(*args,**kwargs):ifclsnotininstances:instances[cls]=cls(*args,**kwargs)returninstances[cls]return_singleton@singletonclassSelfClass(object):passdefmain():s1=SelfClass()s2=SelfClass()asserts1iss2if__name__=='__main__':main()

‘柒’ PYTHON里的装饰器能装饰类吗

可以的啦

#-*-coding:UTF-8-*-
fromfunctoolsimportwraps

__author__='lpe234'


defsingleton(cls):
"""
装饰器实现单例模式
:paramcls:
:return:
"""
instances={}

@wraps(cls)
def_singleton(*args,**kwargs):
ifclsnotininstances:
instances[cls]=cls(*args,**kwargs)
returninstances[cls]
return_singleton


@singleton
classSelfClass(object):
pass


defmain():
s1=SelfClass()
s2=SelfClass()
asserts1iss2

if__name__=='__main__':
main()

‘捌’ 网页页面设计过程中python设计如何与其结合,代码植入方法与核心技术流程举例

摘要 您好。

‘玖’ Python 有什么奇技淫巧

Python奇技淫巧
当发布python第三方package时, 并不希望代码中所有的函数或者class可以被外部import, 在 __init__.py 中添加 __all__ 属性,

该list中填写可以import的类或者函数名, 可以起到限制的import的作用, 防止外部import其他函数或者类

#!/usr/bin/env python
# -*- 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:
print line

详细原理可以查看这篇文章, 浅谈 Python 的 with 语句

知道具体原理, 我们可以自定义支持上下文管理协议的类, 类中实现 __enter__ 和 __exit__ 方法
#!/usr/bin/env python
# -*- 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"Exited without Exception"
returnTrue
else:
print"Exited with Exception"
returnFalse

deftest_with():
withMyWith()asmy_with:
print"running my_with"
print"------分割线-----"
withMyWith()asmy_with:
print"running before Exception"
raiseException
print"running after Exception"

if__name__ =='__main__':
test_with()

执行结果如下:
__init__ method
__enter__ method
running my_with
__exit__ method
ExitedwithoutException
------分割线-----
__init__ method
__enter__ method
running before Exception
__exit__ method
ExitedwithException
Traceback(most recent call last):
File"bin/python", line34,in<mole>
exec(compile(__file__f.read(), __file__, "exec"))
File"test_with.py", line33,in<mole>
test_with()
File"test_with.py", line28,intest_with
raiseException
Exception

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

filter的用法

相对 filter 而言, map和rece使用的会更频繁一些, 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]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/env python
# -*- coding: utf-8 -*-

classA(object):

# 普通成员函数
deffoo(self, x):
print "executing foo(%s, %s)"% (self, x)

@classmethod# 使用classmethod进行装饰
defclass_foo(cls, x):
print "executing class_foo(%s, %s)"% (cls, x)

@staticmethod# 使用staticmethod进行装饰
defstatic_foo(x):
print "executing static_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()

# 函数输出
executing foo(<__main__.Aobject at0x100ba4e10>, para)
executing class_foo(<class'__main__.A'>,para)
executing class_foo(<class'__main__.A'>,para)
executing static_foo(para)
executing static_foo(para)

property装饰器

定义私有类属性

将 property 与装饰器结合实现属性私有化( 更简单安全的实现get和set方法 )
#python内建函数
property(fget=None, fset=None, fdel=None, doc=None)

fget 是获取属性的值的函数, fset 是设置属性值的函数, fdel 是删除属性的函数, doc 是一个字符串(like a comment).从实现来看,这些参数都是可选的

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('score must be an integer!')
ifvalue <0orvalue >100:
raiseValueError('score must between 0 ~ 100!')
self._score = value

iter魔法

通过yield和 __iter__ 的结合, 我们可以把一个对象变成可迭代的
通过 __str__ 的重写, 可以直接通过想要的形式打印对象
#!/usr/bin/env python
# -*- 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/env python
# -*- 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/env python
# -*- 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 == 5 and test_second(test_first) > 5"
res = eval(condition, action) # 解释condition并根据action对应的动作执行
printres

if__name__ =='_

exec

exec在Python中会忽略返回值, 总是返回None, eval会返回执行代码或语句的返回值
exec 和 eval 在执行代码时, 除了返回值其他行为都相同
在传入字符串时, 会使用 compile(source, '<string>', mode) 编译字节码. mode的取值为 exec 和 eval
#!/usr/bin/env python
# -*- 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]) Return the value of
the named attribute of object. name must be a string. If the string is
the name of one of the object’s attributes, the result is the value of
that attribute. For example, getattr(x, ‘foobar’) is equivalent to
x.foobar. If the named attribute does not exist, default is returned if
provided, otherwise AttributeError is raised.

通过string类型的name, 返回对象的name属性(方法)对应的值, 如果属性不存在, 则返回默认值, 相当于object.name
# 使用范例
classTestGetAttr(object):

test = "test attribute"

defsay(self):
print"test method"

deftest_getattr():
my_test = TestGetAttr()
try:
printgetattr(my_test,"test")
exceptAttributeError:
print"Attribute Error!"
try:
getattr(my_test, "say")()
exceptAttributeError:# 没有该属性, 且没有指定返回值的情况下
print"Method Error!"

if__name__ =='__main__':
test_getattr()

# 输出结果
test attribute
test method

命令行处理
defprocess_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
ifargvisNone:
argv = sys.argv[1:]

# initialize the parser object:
parser = optparse.OptionParser(
formatter=optparse.TitledHelpFormatter(width=78),
add_help_option=None)

# define options here:
parser.add_option( # customized description; put --help last
'-h','--help', action='help',
help='Show this help message and exit.')

settings, args = parser.parse_args(argv)

# check number of arguments, verify values, etc.:
ifargs:
parser.error('program takes no command-line arguments; '
'"%s" ignored.'% (args,))

# further process settings & args if necessary

returnsettings, args

defmain(argv=None):
settings, args = process_command_line(argv)
# application code here, 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) # 多行写入

各种时间形式转换

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

字符串格式化

一个非常好用, 很多人又不知道的功能
>>>name ="andrew"
>>>"my name is {name}".format(name=name)
'my name is andrew'

阅读全文

与装饰器模式python相关的资料

热点内容
安卓手机浏览器怎么扫二维码 浏览:715
通达信成本均线源码 浏览:614
可以下载的解压音频 浏览:564
海贼王怎么换服务器 浏览:318
计算机上的共享文件夹映射 浏览:940
荣耀安装包在文件夹哪里 浏览:195
机票php源码 浏览:231
linux共享mac 浏览:922
中国没有国外的服务器地址 浏览:759
为什么退款服务器连接错误 浏览:557
android短信存储位置 浏览:972
unix网络编程卷4 浏览:808
找靓机app下单什么时候发货 浏览:413
android一个应用两个进程 浏览:803
linux硬盘复制 浏览:808
php图片服务器搭建 浏览:801
下载压缩文件怎么打开 浏览:194
新建文件夹叫什么名字 浏览:567
windows20的开机命令 浏览:335
微信一般在电脑的那个文件夹 浏览:511