python - 在 python 中观察变量?

标签 python reference

在 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/

相关文章:

Java String += 需要速记解释

c++ - 试图引用已删除的函数(未引用已创建的函数)

python - 模拟 Python 对象实例化

python - 当只有一组时,Groupby apply 会进行不需要的转置

python - 如何减去这两个日期?如何计算他们之间的分钟数?

引用变量的 C++ 初始化列表

python - 如何从 Python 向游戏发送方向盘/操纵杆输入?

python - 如何在 TensorFlow 数字识别中使用自己的手绘图像

reference - 了解 Vec<T> 的调试实现

php - 如何使用 HTML 链接将变量从一个 PHP 文件传递​​到另一个文件?