在python中创建一个全局函数 [英] create a global function in python

查看:661
本文介绍了在python中创建一个全局函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,我如何创建一个可以是全局的函数,并在所有被调用的类中使用?
下面是一个例子:

pre $ import configparser
import os
import sys
从datetime导入日期时间
从ftplib导入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()#删除这是修复!
$ b $ class zoneFTP():
def __init __(self):
self.conn = FTP()
self.dir ='./'
notify('dir is:'+ self.dir)

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

if __name__ ==__main__:
main()

调用<$ zoneFTP类中的c $ c> notify()失败。我怎样才能让 notify()函数像内置函数中的一个python一样,以便可以在任何地方调用它?或者是否有更好的方式来完成我在这里完成的工作? 放置 notify ),并让所有其他模块导入它。


In python how can I create a function that can be global an used in all classes that are called? Here is an example:

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()

Calling notify() in the zoneFTP class fails. How can I make the notify() function like one of the python built in functions so that it can be called anywhere? Or is there a better way of doing what I am trying to accomplish here?

解决方案

Put notify() in a utility module and have all the other modules import it.

这篇关于在python中创建一个全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆