Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

create a global function in python

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...