自引用多个不同的对象而不是一个

Self references several different objects instead of one

我有一个 class 有一个创建时间表的方法(为了简单起见,它被简化了):

def create_schedule(self):
    # Create a function-1 event
    scheduler.add_job(self.function_1,
                      trigger='date',
                      run_date=datetime_1,
                      args=[self])

    # Create a function-2 event
    scheduler.add_job(self.function_2,
                      trigger='date',
                      run_date=datetime_2,
                      args=[self])

这些是 class function_1function_2 方法:

def function_1(self, *args):
    print('self in function_1:', self)

def function_2(self, *args):
    print('self in function_2:', self)

出于某种原因,当它从调度程序执行两个事件时,会打印以下内容:

self in function_1: <program.my_class object at 0x6f03e430>
self in function_2: <program.my_class object at 0x6f03e4b0>

即两者是不同的对象,因此 function_1 所做的更改不会出现在 function_2 中,反之亦然。

这是为什么? self 指向的所有实例不应该相同吗?有没有办法绕过这个并强制所有 selfs 实际上指向同一个实例?

您使用 apscheduler 注册了两个不同的事件,在您的配置中存储了您的事件回调信息 in a database in a serialized form:

Job stores house the scheduled jobs. The default job store simply keeps the jobs in memory, but others store them in various kinds of databases. A job’s data is serialized when it is saved to a persistent job store, and deserialized when it’s loaded back from it.

大胆强调我的。

您拥有的两个作业是独立执行的,因此它们被独立反序列化,导致从序列化数据创建两个新实例。

您不能指望不同的事件对同一实例起作用。您需要通过添加足够的识别信息来外部化您的状态,以便在作业触发时重新创建状态。