I have a question concerning variables and passing them to class methods. I have a script OM with the class OM in it.
class OM:
def __init__( Self , Debug_Mode = False ):
print( "Initialized" )
Self.Debug_Mode = Debug_Mode
Self.Registered_Modules = { }
I also have this config script :
class Config:
def __init__( Self ) :
OM = __import__( 'OM' )
Self.OM = OM.OM.Load_Module( )
print( Self.OM )
Self.Config_Entries = { }
As the script OM has been already called, I want to hand over the instance object WITHOUT calling it. For this reason, I printed 'Initialized' in my __init__
function.
When I execute my file, the "Initialized' string will be printed 2 times because it has been initialized before by my start script :
class VTE:
def __init__( Self ) :
Self.OM = OM( Debug_Mode = False )
CFG = Self.OM.Load_Module( 'Config' )
CFG.Config_Loader( )
What do I have to change here for importing the instance ( like <OM.OM object at x000002047D4ACC10>
) without calling it again :
OM = __import__( 'OM' )
Self.OM = OM.OM( )
print( Self.OM )
Self.Config_Entries = { }
Thanks a lot and best regards.
EDIT :
I now figured out how to do it. The instance of the module OM
is in Self
,
so i defined a variable OM_Handler
outside of __init__( )
. Inside Of __init__
, i assigned Self
to OM_Handler
:
class OM :
OM_Handler = "None"
def __init__( Self , Debug_Mode = False ) :
OM.OM_Handler = Self
Self.Debug_Mode = Debug_Mode
Self.Registered_Modules = { }
Afterwards, i'm able to call the instance object in my config file :
class Config( ) :
def __init__( Self ) :
Self.Config_Entries = { }
OM = __import__( 'OM' )
OM_Handler = OM.OM.OM_Handler
Self.OM = OM_Handler
print( Self.OM )
Prints <OM.OM object at 0x0000026F5812DFA0>
But i'm not quite sure, if this is the best solution. I have been told, that global variables are strictly forbidden or rather have a bad repute.I hope, you will give me some advices.
Best regards NumeroUnoDE
You are confusing the concepts of "module" and "class" here. That distinction is especially important when you have a module and a class with the same name. If your INTENTION is to have a singleton OM object (one global for the whole app), you can do that by having OM.py look like this.
class OM:
def __init__( self , Debug_Mode = False ):
print( "Initialized" )
self.Debug_Mode = Debug_Mode
self.Registered_Modules = { }
OM = OM()
Now, in your main code, or in any module where you need it, you can write:
...
import OM
class Config():
def __init__( self ):
self.OM = OM.OM
Or, even simpler:
from OM import OM
class Config():
def __init__( self ):
self.OM = OM
It's not good practice to capitalize variable names, and it is ESPECIALLY bad to capitalize the name self
. That spelling is an international standard in Python. It's not technically a reserved word, but it might as well be.