Skip to main content
 首页 » 编程设计

python之在 python 中观察变量

2024年10月24日2052php

在 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