【问题标题】:Run a class-method every n seconds每 n 秒运行一个类方法
【发布时间】:2014-11-14 23:34:33
【问题描述】:

我尝试每隔 n 秒在 Python 3 中运行一个类方法。

我认为Threading 会是一个好方法。问题 (Run certain code every n seconds) 展示了如何在没有对象的情况下做到这一点。

我尝试像这样将这段代码“转移”到 OOP:

class Test:
    import threading
    def printit():
        print("hello world")
        threading.Timer(5.0, self.printit).start()

test = Test()
test.printit()

>> TypeError: printit() takes no arguments (1 given)

我收到此错误。

你能帮我做对吗?

【问题讨论】:

  • 您的方法定义不正确。您缺少 self 参数
  • 你是对的。我有点惭愧:O
  • 每个人都会在某一时刻发生。您定义的是静态方法。如果你的类真的不包含任何数据,并且只有这个方法,你应该保持原样并使用Test.printit()
  • 附带说明,您真的不想在类定义中使用import。 (在极少数情况下它可能有意义,但这不是其中之一。)在顶层,在脚本的顶部执行。
  • 这是 OP 所说的 Python 3.x,没有未绑定的函数。 Python 有它自己的定义是很公平的,但我觉得这种用法完全是在它的头脑中。 “类的可调用成员不能也不能访问类的实例,并且可以通过对类的引用来调用,这不是静态方法。相反,它是不可调用的实例方法。它只是一个静态方法方法一旦你应用了这个装饰器,我们就会给你 uncurries 它并混淆调用签名,因此它可以作为实例方法调用。”对我来说没有多大意义。

标签: python multithreading python-3.x repeat


【解决方案1】:

将参数 self 添加到 printit 方法中,它对我有用。此外,import 语句应该在文件的顶部,而不是在类定义中。

import threading

class Test:
    def printit(self):
        print("hello world")
        threading.Timer(5.0, self.printit).start()

test = Test()
test.printit()

【讨论】:

  • 别担心,我们所有人都会遇到!
猜你喜欢
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 2012-07-11
  • 2011-03-24
  • 2020-07-15
  • 2022-12-11
相关资源
最近更新 更多