首页 > 解决方案 > Why does my my class method fail to print output?

问题描述

i am trying to code an automated notification system which returns a notification (Michael) based on a certain day and time. i used a class object but when it calls the allocated method, it returns no output. the code gives no error which makes it all confusing. i ran the code 2 minutes earlier and when the current time came, nothing happened. this is my first python project.

#import required modules

import datetime

from datetime import date

import calendar


#Get the variable for time right mow

dt = datetime.datetime.now()

#remove the millisecond

x = dt.strftime("%H:%M:%S")

#define class

class Change:
    def __init__(self):
        # define value for date_str argument in mon method
        self.date_str = x

    def mon(self, date_str):
        if date_str == "10:22:00":
            print('michael')

#class instantiation via object
#set value for today's day name

my_date = date.today()

Today = calendar.day_name[my_date.weekday()]

if Today == 'Thursday':

    if x == "10:22:00":

        #call object when if statement is true
        assembly_end_mental_maths_starts = Change()
        assembly_end_mental_maths_starts.mon("10:22:00")

标签: pythonclassobjectmethodsoutput

解决方案


在我看来,这是一个经典的XY 问题

但首先你的问题,正如@ForceBru所说,你是否在那个时候运行程序以让它触发,即使这样,如果你循环它也不是一个好的解决方案,因为条件需要在那一秒触发,这可能会在循环周期之间传递。您正在寻找的是schedule

如何在 Python 中获得类似 Cron 的调度程序?[关闭]

import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

推荐阅读