简体   繁体   English

Python:尝试避免对time_passed函数使用全局变量

[英]Python: trying to avoid using a global variable for a time_passed function

I am new to Python and am using a method time_passed() for keeping track of how much time has passed. 我是Python的新手,正在使用time_passed()方法跟踪经过了多少时间。

I would prefer not to use a global variable. 我宁愿不使用全局变量。 Is there a way to write this method so that it doesn't take any parameters and it doesn't use a global variable? 有没有一种方法可以编写此方法,使其不使用任何参数,并且不使用全局变量?

import time

start_time=time.time()    
def time_passed():
    return time.time() - start_time

What is the pythonic way to handle this? 处理此问题的pythonic方法是什么?

The static variable equivalent in Python is similar to Javascript where assigning a variable under a particular object namespace gives it persistence outside of method scope it was assigned in. Just like in Javascript, Python functions are objects and can be assigned member variables. 在Python中等效的静态变量类似于Javascript,在特定的对象名称空间下分配变量使其在其分配的方法范围之外具有持久性。就像在Javascript中一样,Python函数是对象,并且可以分配成员变量。

So for this example you could write 所以对于这个例子,你可以写

import time

def timestamp():
    timestamp.start_time=time.time()
    return time.time() - timestamp.start_time

Edit: now looking at the code however, you clearly want to initialize once and this function will reinitialize start_time per call. 编辑:但是现在看代码,您显然想要初始化一次,并且此函数将重新初始化每个调用的start_time。 I am not so experienced in Python but this may work 我对Python不那么有经验,但这可能有用

import time

def timestamp():
    if timestamp.start_time is None:
        timestamp.start_time=time.time()
    return time.time() - timestamp.start_time

You can write a simple class storing the start time: 您可以编写一个简单的类来存储开始时间:

import time

class Timer:
    def __init__(self):
        self.start = time.time()

    def __call__(self):
        return time.time() - self.start

Then use it like: 然后像这样使用它:

time_passed = Timer()
print time_passed()

This way you can easily use multiple timers as well. 这样,您也可以轻松使用多个计时器。

Generator should be used for functions that need to encapsulate state. 生成器应用于需要封装状态的函数。

import time


def time_passed_generator():
    start_time = time.time()
    while True:
        yield time.time() - start_time

time_passed = time_passed_generator()

#start

next(time_passed) # should be about 0.0

# ... later get the time passed

print(next(time_passed))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM