Python 如何设置一个随着系统时间变化的动态变量?

2018-04-26 14:24:17 +08:00
 wsds

想取当前时间,但取时间那一坨内容太长了,复制的到处都是,封装一个方法行是行,但感觉有点啰嗦 我是想能不能通过一个动态变量 a 来获取当前时间,能做到吗?直接赋值,取的就是变量生成那一瞬间的固定时间了,不是我想要的,我想要的是 print(a) 就能获取当前时间

>>> a =  time.strftime('%Y-%m-%d %H:%M:%S')
>>> a
'2018-04-26 14:16:17'
>>> a
'2018-04-26 14:16:17'
>>> a
'2018-04-26 14:16:17'
>>>

==================

>>> def a():
...     return time.strftime('%Y-%m-%d %H:%M:%S')
...
>>> a()
'2018-04-26 14:19:36'
>>> a()
'2018-04-26 14:19:39'
>>> a()
'2018-04-26 14:19:41'
>>>

4635 次点击
所在节点    Python
9 条回复
Contextualist
2018-04-26 14:56:11 +08:00
既然要 class 的 repr 为函数的结果,定义 metaclass 的 __repr__
``` python 3
class _a(type):
   def __repr__(self):
      return time.strftime('%Y-%m-%d %H:%M:%S')

class a(object, metaclass = _a):
   pass

print(a)
```
wsds
2018-04-26 15:04:22 +08:00
@Contextualist /惊讶
knightdf
2018-04-26 15:16:15 +08:00
``` python
class A(object):
@property
def a(self):
return time.strftime('%Y-%m-%d %H:%M:%S')
```

print(A().a)
wsds
2018-04-26 15:20:00 +08:00
@knightdf 比直接定义方法还麻烦啊
goreliu
2018-04-26 15:27:44 +08:00
你是嫌定义麻烦还是调用麻烦?定义麻烦的话:

a = lambda:time.strftime('%Y-%m-%d %H:%M:%S')

应该没有更简单的办法了。调用麻烦的话,就一楼。
shintendo
2018-04-26 15:28:53 +08:00
你在提出这个需求的时候,有没有想过这种动态变量,假如有的话,底层要以什么原理来实现?
每隔一个毫秒,系统自动更新一次这个变量所在内存里的值吗?
还是平时不变,只在你取值的时候更新一下?
这后者不就是函数么,还是说你只是想要个省略括号的语法糖?
Shazoo
2018-04-26 15:33:12 +08:00
```python
>>> a = lambda :time.strftime('%Y-%m-%d %H:%M:%S')
>>> a()
'2018-04-26 15:32:20'
>>> a()
'2018-04-26 15:32:23'
>>>
```
lauix
2018-04-26 15:38:39 +08:00
创建动态变量

locals()[变量名] = 变量值
est
2018-04-26 15:40:34 +08:00
import time

now=type('now', (), {'__repr__': lambda s: str(time.time())})()



使用:

In [105]: now
Out[105]: 1524728419.898981

In [106]: now
Out[106]: 1524728420.5150971

In [107]: now
Out[107]: 1524728421.219552

In [108]: now
Out[108]: 1524728425.09097

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/450061

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX