日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python设置时间步长与时间离散格式_python怎么定义时间

發(fā)布時(shí)間:2023/12/20 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python设置时间步长与时间离散格式_python怎么定义时间 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Python 的 Decorator在使用上和Java/C#的Annotation很相似,就是在方法名前面加一個(gè)@XXX注解來為這個(gè)方法裝飾一些東西。但是,Java/C#的Annotation也很讓人望而卻步,太TMD的復(fù)雜了,你要玩它,你需要了解一堆Annotation的類庫文檔,讓人感覺就是在學(xué)另外一門語言。

而Python使用了一種相對(duì)于Decorator Pattern和Annotation來說非常優(yōu)雅的方法,這種方法不需要你去掌握什么復(fù)雜的OO模型或是Annotation的各種類庫規(guī)定,完全就是語言層面的玩法:一種函數(shù)式編程的技巧。如果你看過本站的《函數(shù)式編程》,你一定會(huì)為函數(shù)式編程的那種“描述你想干什么,而不是描述你要怎么去實(shí)現(xiàn)”的編程方式感到暢快。(如果你不了解函數(shù)式編程,那在讀本文之前,還請(qǐng)你移步去看看《函數(shù)式編程》) 好了,我們先來點(diǎn)感性認(rèn)識(shí),看一個(gè)Python修飾器的Hello World的代碼。

Hello World

下面是代碼:文件名:hello.py

def hello(fn):

def wrapper():

print "hello, %s" % fn.__name__

fn()

print "goodby, %s" % fn.__name__

return wrapper

@hellodef foo():

print "i am foo"

foo()

當(dāng)你運(yùn)行代碼,你會(huì)看到如下輸出:

[chenaho@chenhao-air]$ python hello.pyhello, fooi am foogoodby, foo

你可以看到如下的東西:

1)函數(shù)foo前面有個(gè)@hello的“注解”,hello就是我們前面定義的函數(shù)hello

2)在hello函數(shù)中,其需要一個(gè)fn的參數(shù)(這就用來做回調(diào)的函數(shù))

3)hello函數(shù)中返回了一個(gè)inner函數(shù)wrapper,這個(gè)wrapper函數(shù)回調(diào)了傳進(jìn)來的fn,并在回調(diào)前后加了兩條語句。

Decorator 的本質(zhì)

對(duì)于Python的這個(gè)@注解語法糖- Syntactic Sugar 來說,當(dāng)你在用某個(gè)@decorator來修飾某個(gè)函數(shù)func時(shí),如下所示:

@decoratordef func():

pass

其解釋器會(huì)解釋成下面這樣的語句:

func = decorator(func)

尼瑪,這不就是把一個(gè)函數(shù)當(dāng)參數(shù)傳到另一個(gè)函數(shù)中,然后再回調(diào)嗎?是的,但是,我們需要注意,那里還有一個(gè)賦值語句,把decorator這個(gè)函數(shù)的返回值賦值回了原來的func。 根據(jù)《函數(shù)式編程》中的first class functions中的定義的,你可以把函數(shù)當(dāng)成變量來使用,所以,decorator必需得返回了一個(gè)函數(shù)出來給func,這就是所謂的higher order function 高階函數(shù),不然,后面當(dāng)func()調(diào)用的時(shí)候就會(huì)出錯(cuò)。 就我們上面那個(gè)hello.py里的例子來說,

@hellodef foo():

print "i am foo"

被解釋成了:

foo = hello(foo)

是的,這是一條語句,而且還被執(zhí)行了。你如果不信的話,你可以寫這樣的程序來試試看:

def fuck(fn):

print "fuck %s!" % fn.__name__[::-1].upper()

@fuckdef wfg():

pass

沒了,就上面這段代碼,沒有調(diào)用wfg()的語句,你會(huì)發(fā)現(xiàn), fuck函數(shù)被調(diào)用了,而且還很NB地輸出了我們每個(gè)人的心聲!

再回到我們hello.py的那個(gè)例子,我們可以看到,hello(foo)返回了wrapper()函數(shù),所以,foo其實(shí)變成了wrapper的一個(gè)變量,而后面的foo()執(zhí)行其實(shí)變成了wrapper()。

知道這點(diǎn)本質(zhì),當(dāng)你看到有多個(gè)decorator或是帶參數(shù)的decorator,你也就不會(huì)害怕了。

比如:多個(gè)decorator

@decorator_one@decorator_twodef func():

pass

相當(dāng)于:

func = decorator_one(decorator_two(func))

比如:帶參數(shù)的decorator:

@decorator(arg1, arg2)def func():

pass

相當(dāng)于:

func = decorator(arg1,arg2)(func)

這意味著decorator(arg1, arg2)這個(gè)函數(shù)需要返回一個(gè)“真正的decorator”。

帶參數(shù)及多個(gè)Decrorator

我們來看一個(gè)有點(diǎn)意義的例子:html.py

def makeHtmlTag(tag, args, *kwds):

def real_decorator(fn):

css_class = " class='{0}'".format(kwds["css_class"])

if "css_class" in kwds else ""

def wrapped(*args, **kwds):

return "" + fn(*args, **kwds) + ""+tag+">"

return wrapped

return real_decorator

@makeHtmlTag(tag="b", css_class="bold_css")@makeHtmlTag(tag="i", css_class="italic_css")def hello():

return "hello world"

print hello()

輸出:

hello world

在上面這個(gè)例子中,我們可以看到:makeHtmlTag有兩個(gè)參數(shù)。所以,為了讓 hello = makeHtmlTag(arg1, arg2)(hello) 成功,makeHtmlTag 必需返回一個(gè)decorator(這就是為什么我們?cè)趍akeHtmlTag中加入了real_decorator()的原因),這樣一來,我們就可以進(jìn)入到 decorator 的邏輯中去了—— decorator得返回一個(gè)wrapper,wrapper里回調(diào)hello。看似那個(gè)makeHtmlTag() 寫得層層疊疊,但是,已經(jīng)了解了本質(zhì)的我們覺得寫得很自然。

你看,Python的Decorator就是這么簡單,沒有什么復(fù)雜的東西,你也不需要了解過多的東西,使用起來就是那么自然、體貼、干爽、透氣,獨(dú)有的速效凹道和完美的吸收軌跡,讓你再也不用為每個(gè)月的那幾天感到焦慮和不安,再加上貼心的護(hù)翼設(shè)計(jì),量多也不用當(dāng)心。對(duì)不起,我調(diào)皮了。

什么,你覺得上面那個(gè)帶參數(shù)的Decorator的函數(shù)嵌套太多了,你受不了。好吧,沒事,我們看看下面的方法。

class式的 Decorator

首先,先得說一下,decorator的class方式,還是看個(gè)示例:

class myDecorator(object):

def __init__(self, fn):

print "inside myDecorator.__init__()"

self.fn = fn

def __call__(self):

self.fn()

print "inside myDecorator.__call__()"

@myDecoratordef aFunction():

print "inside aFunction()"

print "Finished decorating aFunction()"

aFunction()

輸出:

inside myDecorator.__init__()

Finished decorating aFunction()

inside aFunction()

inside myDecorator.__call__()

上面這個(gè)示例展示了,用類的方式聲明一個(gè)decorator。我們可以看到這個(gè)類中有兩個(gè)成員:1)一個(gè)是__init__(),這個(gè)方法是在我們給某個(gè)函數(shù)decorator時(shí)被調(diào)用,所以,需要有一個(gè)fn的參數(shù),也就是被decorator的函數(shù)。2)一個(gè)是__call__(),這個(gè)方法是在我們調(diào)用被decorator函數(shù)時(shí)被調(diào)用的。上面輸出可以看到整個(gè)程序的執(zhí)行順序。

這看上去要比“函數(shù)式”的方式更易讀一些。

下面,我們來看看用類的方式來重寫上面的html.py的代碼:html.py

class makeHtmlTagClass(object):

def __init__(self, tag, css_class=""):

self._tag = tag

self._css_class = " class='{0}'".format(css_class)

if css_class !="" else ""

def __call__(self, fn):

def wrapped(*args, **kwargs):

return ""

+ fn(*args, **kwargs) + "" + self._tag + ">"

return wrapped

@makeHtmlTagClass(tag="b", css_class="bold_css")@makeHtmlTagClass(tag="i", css_class="italic_css")def hello(name):

return "Hello, {}".format(name)

print hello("Hao Chen")

上面這段代碼中,我們需要注意這幾點(diǎn):1)如果decorator有參數(shù)的話,__init__() 成員就不能傳入fn了,而fn是在__call__的時(shí)候傳入的。2)這段代碼還展示了 wrapped(args, *kwargs) 這種方式來傳遞被decorator函數(shù)的參數(shù)。(其中:args是一個(gè)參數(shù)列表,kwargs是參數(shù)dict,具體的細(xì)節(jié),請(qǐng)參考Python的文檔或是StackOverflow的這個(gè)問題,這里就不展開了)

用Decorator設(shè)置函數(shù)的調(diào)用參數(shù)

你有三種方法可以干這個(gè)事:

第一種,通過 **kwargs,這種方法decorator會(huì)在kwargs中注入?yún)?shù)。

def decorate_A(function):

def wrap_function(*args, **kwargs):

kwargs['str'] = 'Hello!'

return function(*args, **kwargs)

return wrap_function

@decorate_Adef print_message_A(args, *kwargs):

print(kwargs['str'])

print_message_A()

第二種,約定好參數(shù),直接修改參數(shù)

def decorate_B(function):

def wrap_function(*args, **kwargs):

str = 'Hello!'

return function(str, *args, **kwargs)

return wrap_function

@decorate_Bdef print_message_B(str, args, *kwargs):

print(str)

print_message_B()

第三種,通過 *args 注入

def decorate_C(function):

def wrap_function(*args, **kwargs):

str = 'Hello!'

#args.insert(1, str)

args = args +(str,)

return function(*args, **kwargs)

return wrap_function

class Printer:

@decorate_C

def print_message(self, str, *args, **kwargs):

print(str)

p = Printer()p.print_message()

Decorator的副作用

到這里,我相信你應(yīng)該了解了整個(gè)Python的decorator的原理了。

相信你也會(huì)發(fā)現(xiàn),被decorator的函數(shù)其實(shí)已經(jīng)是另外一個(gè)函數(shù)了,對(duì)于最前面那個(gè)hello.py的例子來說,如果你查詢一下foo.__name__的話,你會(huì)發(fā)現(xiàn)其輸出的是“wrapper”,而不是我們期望的“foo”,這會(huì)給我們的程序埋一些坑。所以,Python的functool包中提供了一個(gè)叫wrap的decorator來消除這樣的副作用。下面是我們新版本的hello.py。文件名:hello.py

from functools import wrapsdef hello(fn):

@wraps(fn)

def wrapper():

print "hello, %s" % fn.__name__

fn()

print "goodby, %s" % fn.__name__

return wrapper

@hellodef foo():

'''foo help doc'''

print "i am foo"

pass

foo()print foo.__name__ #輸出 fooprint foo.__doc__ #輸出 foo help doc

當(dāng)然,即使是你用了functools的wraps,也不能完全消除這樣的副作用。

來看下面這個(gè)示例:

from inspect import getmembers, getargspecfrom functools import wraps

def wraps_decorator(f):

@wraps(f)

def wraps_wrapper(*args, **kwargs):

return f(*args, **kwargs)

return wraps_wrapper

class SomeClass(object):

@wraps_decorator

def method(self, x, y):

pass

obj = SomeClass()for name, func in getmembers(obj, predicate=inspect.ismethod):

print "Member Name: %s" % name

print "Func Name: %s" % func.func_name

print "Args: %s" % getargspec(func)[0]

輸出:

Member Name: method

Func Name: method

Args: []

你會(huì)發(fā)現(xiàn),即使是你你用了functools的wraps,你在用getargspec時(shí),參數(shù)也不見了。

要修正這一問,我們還得用Python的反射來解決,下面是相關(guān)的代碼:

def get_true_argspec(method):

argspec = inspect.getargspec(method)

args = argspec[0]

if args and args[0] == 'self':

return argspec

if hasattr(method, '__func__'):

method = method.__func__

if not hasattr(method, 'func_closure') or method.func_closure is None:

raise Exception("No closure for method.")

method = method.func_closure[0].cell_contents

return get_true_argspec(method)

當(dāng)然,我相信大多數(shù)人的程序都不會(huì)去getargspec。所以,用functools的wraps應(yīng)該夠用了。

一些decorator的示例

好了,現(xiàn)在我們來看一下各種decorator的例子:

給函數(shù)調(diào)用做緩存

這個(gè)例實(shí)在是太經(jīng)典了,整個(gè)網(wǎng)上都用這個(gè)例子做decorator的經(jīng)典范例,因?yàn)樘?jīng)典了,所以,我這篇文章也不能免俗。

from functools import wrapsdef memo(fn):

cache = {}

miss = object()

@wraps(fn)

def wrapper(*args):

result = cache.get(args, miss)

if result is miss:

result = fn(*args)

cache[args] = result

return result

return wrapper

@memodef fib(n):

if n < 2:

return n

return fib(n - 1) + fib(n - 2)

上面這個(gè)例子中,是一個(gè)斐波拉契數(shù)例的遞歸算法。我們知道,這個(gè)遞歸是相當(dāng)沒有效率的,因?yàn)闀?huì)重復(fù)調(diào)用。比如:我們要計(jì)算fib(5),于是其分解成fib(4) + fib(3),而fib(4)分解成fib(3)+fib(2),fib(3)又分解成fib(2)+fib(1)…… 你可看到,基本上來說,fib(3), fib(2), fib(1)在整個(gè)遞歸過程中被調(diào)用了兩次。

而我們用decorator,在調(diào)用函數(shù)前查詢一下緩存,如果沒有才調(diào)用了,有了就從緩存中返回值。一下子,這個(gè)遞歸從二叉樹式的遞歸成了線性的遞歸。

Profiler的例子

這個(gè)例子沒什么高深的,就是實(shí)用一些。

import cProfile, pstats, StringIO

def profiler(func):

def wrapper(*args, **kwargs):

datafn = func.__name__ + ".profile" # Name the data file

prof = cProfile.Profile()

retval = prof.runcall(func, *args, **kwargs)

#prof.dump_stats(datafn)

s = StringIO.StringIO()

sortby = 'cumulative'

ps = pstats.Stats(prof, stream=s).sort_stats(sortby)

ps.print_stats()

print s.getvalue()

return retval

return wrapper

注冊(cè)回調(diào)函數(shù)

下面這個(gè)示例展示了通過URL的路由來調(diào)用相關(guān)注冊(cè)的函數(shù)示例:

class MyApp():

def __init__(self):

self.func_map = {}

def register(self, name):

def func_wrapper(func):

self.func_map[name] = func

return func

return func_wrapper

def call_method(self, name=None):

func = self.func_map.get(name, None)

if func is None:

raise Exception("No function registered against - " + str(name))

return func()

app = MyApp()

@app.register('/')def main_page_func():

return "This is the main page."

@app.register('/next_page')def next_page_func():

return "This is the next page."

print app.call_method('/')print app.call_method('/next_page')

注意:1)上面這個(gè)示例中,用類的實(shí)例來做decorator。2)decorator類中沒有__call__(),但是wrapper返回了原函數(shù)。所以,原函數(shù)沒有發(fā)生任何變化。

給函數(shù)打日志

下面這個(gè)示例演示了一個(gè)logger的decorator,這個(gè)decorator輸出了函數(shù)名,參數(shù),返回值,和運(yùn)行時(shí)間。

from functools import wrapsdef logger(fn):

@wraps(fn)

def wrapper(*args, **kwargs):

ts = time.time()

result = fn(*args, **kwargs)

te = time.time()

print "function = {0}".format(fn.__name__)

print " arguments = {0} {1}".format(args, kwargs)

print " return = {0}".format(result)

print " time = %.6f sec" % (te-ts)

return result

return wrapper

@loggerdef multipy(x, y):

return x * y

@loggerdef sum_num(n):

s = 0

for i in xrange(n+1):

s += i

return s

print multipy(2, 10)print sum_num(100)print sum_num(10000000)

上面那個(gè)打日志還是有點(diǎn)粗糙,讓我們看一個(gè)更好一點(diǎn)的(帶log level參數(shù)的):

import inspectdef get_line_number():

return inspect.currentframe().f_back.f_back.f_lineno

def logger(loglevel):

def log_decorator(fn):

@wraps(fn)

def wrapper(*args, **kwargs):

ts = time.time()

result = fn(*args, **kwargs)

te = time.time()

print "function = " + fn.__name__,

print " arguments = {0} {1}".format(args, kwargs)

print " return = {0}".format(result)

print " time = %.6f sec" % (te-ts)

if (loglevel == 'debug'):

print " called_from_line : " + str(get_line_number())

return result

return wrapper

return log_decorator

但是,上面這個(gè)帶log level參數(shù)的有兩具不好的地方,1) loglevel不是debug的時(shí)候,還是要計(jì)算函數(shù)調(diào)用的時(shí)間。2) 不同level的要寫在一起,不易讀。

我們?cè)俳又倪M(jìn):

import inspect

def advance_logger(loglevel):

def get_line_number():

return inspect.currentframe().f_back.f_back.f_lineno

def _basic_log(fn, result, *args, **kwargs):

print "function = " + fn.__name__,

print " arguments = {0} {1}".format(args, kwargs)

print " return = {0}".format(result)

def info_log_decorator(fn):

@wraps(fn)

def wrapper(*args, **kwargs):

result = fn(*args, **kwargs)

_basic_log(fn, result, args, kwargs)

return wrapper

def debug_log_decorator(fn):

@wraps(fn)

def wrapper(*args, **kwargs):

ts = time.time()

result = fn(*args, **kwargs)

te = time.time()

_basic_log(fn, result, args, kwargs)

print " time = %.6f sec" % (te-ts)

print " called_from_line : " + str(get_line_number())

return wrapper

if loglevel is "debug":

return debug_log_decorator

else:

return info_log_decorator

你可以看到兩點(diǎn),1)我們分了兩個(gè)log level,一個(gè)是info的,一個(gè)是debug的,然后我們?cè)谕馕哺鶕?jù)不同的參數(shù)返回不同的decorator。2)我們把info和debug中的相同的代碼抽到了一個(gè)叫_basic_log的函數(shù)里,DRY原則。

一個(gè)MySQL的Decorator

下面這個(gè)decorator是我在工作中用到的代碼,我簡化了一下,把DB連接池的代碼去掉了,這樣能簡單點(diǎn),方便閱讀。

import umysqlfrom functools import wraps

class Configuraion:

def __init__(self, env):

if env == "Prod":

self.host = "coolshell.cn"

self.port = 3306

self.db = "coolshell"

self.user = "coolshell"

self.passwd = "fuckgfw"

elif env == "Test":

self.host = 'localhost'

self.port = 3300

self.user = 'coolshell'

self.db = 'coolshell'

self.passwd = 'fuckgfw'

def mysql(sql):

_conf = Configuraion(env="Prod")

def on_sql_error(err):

print err

sys.exit(-1)

def handle_sql_result(rs):

if rs.rows > 0:

fieldnames = [f[0] for f in rs.fields]

return [dict(zip(fieldnames, r)) for r in rs.rows]

else:

return []

def decorator(fn):

@wraps(fn)

def wrapper(*args, **kwargs):

mysqlconn = umysql.Connection()

mysqlconn.settimeout(5)

mysqlconn.connect(_conf.host, _conf.port, _conf.user,

_conf.passwd, _conf.db, True, 'utf8')

try:

rs = mysqlconn.query(sql, {})

except umysql.Error as e:

on_sql_error(e)

data = handle_sql_result(rs)

kwargs["data"] = data

result = fn(*args, **kwargs)

mysqlconn.close()

return result

return wrapper

return decorator

@mysql(sql = "select * from coolshell" )def get_coolshell(data):

... ...

... ..

線程異步

下面量個(gè)非常簡單的異步執(zhí)行的decorator,注意,異步處理并不簡單,下面只是一個(gè)示例。

from threading import Threadfrom functools import wraps

def async(func):

@wraps(func)

def async_func(*args, **kwargs):

func_hl = Thread(target = func, args = args, kwargs = kwargs)

func_hl.start()

return func_hl

return async_func

if name == '__main__':

from time import sleep

@async

def print_somedata():

print 'starting print_somedata'

sleep(2)

print 'print_somedata: 2 sec passed'

sleep(2)

print 'print_somedata: 2 sec passed'

sleep(2)

print 'finished print_somedata'

def main():

print_somedata()

print 'back in main'

print_somedata()

print 'back in main'

main()

其它

總結(jié)

以上是生活随笔為你收集整理的python设置时间步长与时间离散格式_python怎么定义时间的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。