在Python中创建全局函数

6 投票
1 回答
15629 浏览
提问于 2025-04-16 16:16

在Python中,我该如何创建一个可以在所有类中使用的全局函数呢?这里有个例子:

import configparser
import os
import sys
from datetime import datetime
from ftplib import FTP

def notify(msg):
    echo = True
    log = True
    if echo:
        print(msg)
    if log:
        f = open('log.txt','a')
        msg = datetime.now().strftime("%y-%m-%d-%H:%M:%S")+': ' + msg
        f.write(msg)
        f.close()
    #sys.exit()  #removing this was the fix!

class zoneFTP():
    def __init__(self):
        self.conn = FTP()
        self.dir = './'
        notify('The dir is :' + self.dir)

def main():
    notify('starting')
    ftp = zoneFTP()

if __name__ == "__main__":
    main()

在zoneFTP类中调用notify()时失败了。我该如何让notify()函数像Python内置函数那样,可以在任何地方调用?或者有没有更好的方法来实现我想要的功能呢?

1 个回答

7

notify() 放在一个工具模块里,然后让其他所有模块都去导入它。

撰写回答