Python 3, one class used across multiple modules

纵饮孤独 提交于 2020-01-16 18:45:06

问题


I would like to use the following class across multiple modules without needing log = InitLog() in every module. I need to be able to use ONE defined class variable (in this example log) across multiple modules. What is the best way to do this without altering my current code too drastically. Thanks

import os
import sys
import pdb
import fileinput
import Tools


class InitLog:
    def __init__(self):
        pass
    def setLaws(self):
        self.sound = 'off'
        self.engine = 'goo.txt'

    def Update(self):
        while Tools.Locked.State.LogAddress == True: pass
        Tools.Locked.State.LogAddress = True
        try: os.remove(path + '/' + self.dest + '/init.log')
        except: pass

        summery = 'sound: ' + self.sound + '\n'
        summery += 'engine: ' + self.engine + '\n'

        path = os.getcwd()
        if not os.path.exists(self.dest): os.makedirs(self.dest)
        if os.path.isfile(path + '/' + self.dest + '/init.log') == True: os.remove(path + '/' + self.dest + '/init.log')
        with open (path + '/' + self.dest + '/init.log', mode='a', encoding='utf-8') as a_file:
            a_file.write(summery)
        Tools.Locked.State.LogAddress = False


Tools.Locked.State.LogAddress = False
log = InitLog()
log.setLaws()
log.sound = 'on'
log.Update()

回答1:


Create a module called logging which contains log. In other modules use from logging import log.



来源:https://stackoverflow.com/questions/11080862/python-3-one-class-used-across-multiple-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!