在 Class 或另一个函数 Python 中调用一个函数

Call a function in a Class or another fuction Python

我不擅长 Python 类。我知道在这种情况下使用 class 可以解决尝试在函数内调用函数的问题,但我不确定该怎么做。这是一个在开头介绍的变量中添加的设定时间打开网站的脚本。我想在 setTime() 函数中调用 openWebsite() 函数。我确定 class 可以解决我的问题,但我对 Python 有点陌生。

import webbrowser
import time

指定网站、当地时间和所需时间

page = "https://www.twitter.com"
today = time.strftime('%X %x')
timeToOpen = "09:53:36 02/06/22"

打开网页打印功能

def openWebsite():
    webbrowser.open_new(page)
    print("website opened")
    print(today)

开始时将实际直播时间与变量中的指定时间进行比较

def setTime():
    while time.strftime('%X %x') != timeToOpen:
        timeNow = time.strftime('%X %x')
        if timeNow >= timeToOpen:
            print("It's A Match")

我想在这里调用 openWebsite()

            break
        print("waiting!")
        print (timeNow + " vs " + timeToOpen)
        time.sleep(3)

调用函数

setTime()

PS:如果您有任何其他改进代码的建议,我将不胜感激

谢谢, 马格兹

好问题,涉及范围和参数传递方法。

您可以通过多种方式将函数传递给元函数,这可能取决于您使用 case/coding 风格/和 PEP8。有一些相关的答案可能会有所帮助:

How do I pass a method as a parameter in Python

Passing functions with arguments to another function in Python?

对于下面的所有方法,您需要在函数中放置一个参数,例如 'func_a'(如下),然后函数将采用 local/function 范围内的参数名称:

def setTime(func_a):
    '''a function that opens website with
      some conditions(...)'''
    while time.strftime('%X %x') != timeToOpen:
        timeNow = time.strftime('%X %x')
        if timeNow >= timeToOpen:
            print("It's A Match")
            #call your function here
            func_a()
            break
    #..... rest of function

  1. 通过简单地将函数作为参数传递而不调用 ():
setTime(openWebsite)
  1. 如果您 want/need 压缩多个参数,则通过包装在一个元组中:
functions = (openWebsite,some_other_fuction)
#passing like this
setTime(*functions)

像这样写函数参数:

def setTime(open_page,open_page_b):
    ''' code '''
  1. 参数字典:
functions = {'func_a':opneWebsite}
#passing like this
setTime(**functions)

对于 3,您将需要使用:

def setTime(func_a=None):
    ''' code '''

选项 2/3 的逆过程使用 args 或 kwargs 作为参数 分别以 * 或 ** 为前缀,例如:

def setTime(**kwargs):
    ''' code '''

这样路过:

setTime(func=openWebsite)

与:

def setTime(func_a):
    '''a function that opens website with
      some conditions(...)'''
    while time.strftime('%X %x') != timeToOpen:
        timeNow = time.strftime('%X %x')
        if timeNow >= timeToOpen:
            print("It's A Match")
            #call your function here
            kwargs['func_a']()
            break
    #..... rest of function

希望对您有所帮助<^_^>