在 C++ 中,我可以想象通过引用计数器进行构造(见下文),然后函数将取消引用地址来获取值。 python 中可能有类似的东西吗?
类似于:
import time
class Count_Watcher:
def __init__( self, to_watch ):
self.to_watch = to_watch
sleep_watch()
def sleep_watch( self ):
time.sleep( 5 )
print( self.to_watch )
line_counter = 0
separate_thread_printer = Count_Watcher( (?some operator) line_counter )
for line in some_file:
line_counter += 1
每五秒打印一次 line_counter
的“当前”值(如 for 循环的当前值)
最佳答案
原始 int 不起作用,但正如 k4vin 指出的那样,可以引用的任何其他类型的对象都可以。
我们可以使用包含计数的列表来演示这一点,就像 k4vin 所做的那样:
class Watcher(object):
def __init__(self, to_watch):
self.to_watch = to_watch
def print_current_value(self):
print self.to_watch
i = 0
watcher = Watcher(i)
watcher.print_current_value()
# prints 0
i += 3
watcher.print_current_value()
# still prints 0
l = [0]
watcher = Watcher(l)
watcher.print_current_value()
# prints [0]
l[0] += 3
watcher.print_current_value()
# prints [3]
但是将计数保存在列表中有点笨重,因此一种选择是滚动您自己的简单计数器,然后您可以引用它(与列表一样):
class Counter(object):
def __init__(self):
self.count = 0
def __add__(self, incr):
self.count += incr
def __str__(self):
return str(self.count)
c = Counter()
watcher = Watcher(c)
watcher.print_current_value()
# prints 0
c += 3
watcher.print_current_value()
# hooray! prints 3
关于python - 在 python 中观察变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30986639/