How to access a variable from a class of another module - python

I am a total python beginner and I have a variable created in a class of a file commandline_reader.py that I want to access from another script. I tried to do it by making the variable global, which doesn't work.
myscript.py:
from commandline_reader import Commandline_Reader
reader = Commandline_Reader('--get_serial_number')
reader.run()
print output
commandline_reader.py:
class Commandline_Reader:
def __init__(self,argString=''):
global output
output = []
def run(self):
# do stuff
a = 'somevariable'
output.append(a)
When I run myscript.py I always get a NameError: name 'output' is not defined. I've read that this is because global variables are only defined within a module. How do I correctly access the output variable in my script?

ouch. The whole reason object oriented programming takes place is to avoid the use of global variables. Make them instance variables to access them anywhere in the class.
class Commandline_Reader:
def __init__(self,argString=''):
self.output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a) #output is now part of the instance Commandline reader and can be accessed anywhere inside the class.
clr = Commandline_Reader(argstring='--get_serial_number')
clr.run()
print clr.output
>>>['somevariable']

Make output an instance attribute:
class Commandline_Reader:
def __init__(self,argString=''):
self.output = [] # note use of self here
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a) # and here
The access it via the instance:
print reader.output

Maybe class attribute is more appropriate for you?
class Commandline_Reader:
output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a)

Just return the Value from the run() Method
myscript.py:
from commandline_reader import Commandline_Reader
reader = Commandline_Reader('--get_serial_number')
output = reader.run()
print output
commandline_reader.py:
class Commandline_Reader:
def __init__(self,argString=''):
self.output = []
def run(self):
# do stuff
a = 'somevariable'
self.output.append(a)
return self.output

Related

I am trying to update a global variable using a function which is in an imported module. Both files are in the same folder

# zzz.py
def Put(mess):
global Dict
global Lot
print(mess)
Dict = {}
Lot.append(Dict)
# www.py
from zzz import Put
Dict={}
Lot=[Dict]
Put('abcde')
print(Lot)
I get the following error:
NameError: name 'Lot' is not defined
If I place the Put(mess) function in the www.py file it works just fine.
What am I doing wrong ?
Global variables are not able to do what you want (as mentioned in the comment of John Gordon), but you could use a class as a workaround, like this:
Define the class in a module and add the init function with your "global" variables.
class zzz_class():
def __init__(self):
self.Dict = {}
self.Lot = []
# zzz.py
def Put(self, mess):
print(mess)
self.Lot.append(self.Dict)
Then import the class and use the variables and functions from it.
# www.py
from zzz import zzz_class
z = zzz_class()
z.Dict={}
z.Lot=[z.Dict]
z.Put('abcde')
print(z.Lot)
abcde
[{}, {}]

Adding a new object to a class with user-input(input) in python

I am trying to add new objects to a class(emne) but the new instances of the class needs to be created using user input. So i need a way to be able to chose the name for the object and set some of the values of the objects with user input.
I have already tried to create a function that passes the value of the user input into a x = emner(x) to create it but it only returns:
AttributeError: 'str' object has no attribute 'fagKode'
so i think my issue is that the value of the input is created as a string so that it is not understood as a way to create the function
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne():
nyttEmne = input("test:")
nyttEmne=Emne(nyttEmne)
expected result is that the code creates a new instance of the class.
If by choosing a name you mean your fagKode attribute, what you need is:
fagKode = input('Enter code: ')
Emne(fagKode)
You're adding the instances of Enme to the list in the constructor, so you don't need to save them to a variable.
Alternatively, you can handle that in the function:
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
def leggTilEmne():
nyttEmne = input("test:")
enme.append(Emne(nyttEmne))
I'm not sure what exactly you are asking, since you haven't responded to the comments. So,
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne(self, value): # <--- is this what you want
self.nyttEmne= Emne(value)
This is an example of when to use a class method. __init__ should not be appending to a global variable, though. Either 1) have the class method append to a class attribute, or 2) have it return the object and let the caller maintain a global list.
emne = []
class Emne:
emne = []
def __init__(self, fag_kode):
self.fag_kode = fag_kode
self.karakter = ""
#classmethod
def legg_til_emne_1(cls):
nytt_emne = input("test:")
cls.emne.append(cls(nytt_emne))
#classmethod
def legg_til_emne_2(cls):
nyttEmne = input("test:")
return cls(nyttEmne)
Emne.legg_til_emne_1() # Add to Emne.emne
e = Emne.legg_til_emne_2()
emne.append(e)

Python function call within a property of a class

I am trying to use the "setx" function of a Property in a Class to do some processing of date information that I get from excel. I have a few of my own functions that do the data processing which I tested outside the class, and they worked just fine. But when I move them into the class they suddenly become invisible unless I use the self. instance first. When I use the self.My_xldate_as_tuple() method I get an error:
My_xldate_as_tuple() takes 1 positional argument but 2 were given
Even though the code is EXACTLY what i used outside the class before and it worked.
Before moving into the Property Set block, I was doing the processing of date data outside of the class and setting the variables from outside of the class. That gets clunky when I have about 15 different operations that are all based on when the NumDates Property change. I'm showing shortened versions of both the working set of code and the non-working set of code. What is going on with the self. call that changes how the function takes inputs?
Broken Code:
class XLDataClass(object):
_NumDates = []
TupDates = []
def getNumDates(self): return self._NumDates
def setNumDates(self, value):
self._NumDates = value
self.TupDates = list(map(self.My_xldate_as_tuple,value)) #Error here
#This version doesn't work either, since it can't find My_xldate_as_tuple anymore
self.TupDates = list(map(My_xldate_as_tuple,value))
def delNumDates(self):del self._NumDates
NumDates = property(getNumDates,setNumDates,delNumDates,"Ordinal Dates")
#exact copy of the My_xldate_as_tuple function that works outside the class
def My_xldate_as_tuple(Date):
return xlrd.xldate_as_tuple(Date,1)
#Other code and functions here
#end XlDataClass
def GetExcelData(filename,rowNum,titleCol):
csv = np.genfromtxt(filename, delimiter= ",")
NumDates = deque(csv[rowNum,:])
if titleCol == True:
NumDates.popleft()
return NumDates
#Setup
filedir = "C:/Users/blahblahblah"
filename = filedir + "/SamplePandL.csv"
xlData = XLDataClass()
#Put csv data into xlData object
xlData.NumDates= GetExcelData(filename,0,1)
Working Code:
class XLDataClass(object):
NumDates = []
TupDates = []
#Other code and functions here
#end XlDataClass
#exact copy of the same function outside of the class, which works here
def My_xldate_as_tuple(Date):
return xlrd.xldate_as_tuple(Date,1)
def GetExcelData(filename,rowNum,titleCol):
csv = np.genfromtxt(filename, delimiter= ",")
NumDates = deque(csv[rowNum,:])
if titleCol == True:
NumDates.popleft()
return NumDates
#Setup
filedir = "C:/Users/blahblahblah"
filename = filedir + "/SamplePandL.csv"
xlData = XLDataClass()
#Put csv data into xlData object
xlData.NumDates = GetExcelData(filename,0,1)
#same call to the function that was inside the Setx Property of the class, but it works here.
xlData.TupDates = list(map(self.My_xldate_as_tuple,value))
Instance methods in Python require an explicit self in the argument list. Inside the class, you need to write your method definition like:
def My_xldate_as_tuple(self, Date):

Python Variable empty i don't know why

guys i have a problem with my variable.
When i instance my class my variable dossierProd and dossierModif is not empty but when i want use another function she is empty.
import glob
class OBDI:
dossierProd = ""
dossierModif = ""
listeFichierProd = []
listeFichierModif = []
def __init__(self, dossierP, dossierM):
dossierProd = dossierM
dossierModif = dossierM
def recupListeFichier(self):
HERE MY VARIaBLE dossierProd & dossierModif as empty
for fichier in glob.glob(str(self.dossierProd) + '*.csv'):
self.listeFichierProd.append(fichier.replace("\\", "/"))
for fichier in glob.glob(str(self.dossierModif) + '*.csv'):
self.listeFichierModif.append(fichier.replace("\\", "/"))
if len(self.listeFichierProd) != len(self.listeFichierModif):
print "toto
Have you got an idea why my variable is empty ?
Thx to your response.
Sorry for my bad english ;)
Oh thanks, this error is so stupid.
I'm to be accustomed to java
You haven't initialized dossierP and dossierM instance variables in __init__():
def __init__(self, dossierP, dossierM):
self.dossierProd = dossierM
self.dossierModif = dossierM
Watch self. here.
Also, since it appears that dossierProd and dossierModif variables make sense only for when you have an instance of a OBDI class, remove dossierProd = "" and dossierModif = "" lines.
Also, you probably don't want to share listeFichierProd and listeFichierModif lists between OBDI class instances - initialize lists in __init__():
def __init__(self, dossierP, dossierM):
self.dossierProd = dossierM
self.dossierModif = dossierM
self.listeFichierProd = []
self.listeFichierModif = []
and remove listeFichierProd = [] and listeFichierModif = [] lines.
Make sure you understand what is discussed in the following threads:
Instance variables vs. class variables in Python
python class instance variables and class variables
Hope that helps.

Python Cross Module Variables

I realize there are other threads addressing this problem but as I am fairly new to 'Classes' and have already constructed my class structure ... I would like to find a method that I can integrate into my code. I'm sure this will NOT be a difficult one to answer!
First File: NameResult.py
from NameAssign import *
NameList = NameWorks()
print(NameList.InputNames(NameVar))
Second File: NameAssign.py
class NameWorks:
def __init__(self, NameVar = []):
self.NameVar = NameVar
def InputNames(self, NameVar):
global NameVar
NameVar = ['harry', 'betty', 'sam']
Result:
NameError: name 'NameVar' is not defined
All replies are much appreciated ...
NameVar is not defined in NameAssign; it only exists within NameAssign.NameWorks.InputNames() as a local variable. The easiest way to fix this is to define it in NameAssign at the global level.
Edit:
It turns out that this is what you want to do:
NameResult.py
import NameAssign
namelist = NameAssign.NameWorks(['harry', 'betty', 'sam'])
print namelist.InputNames() # or print(...) for Py3k
NameAssign.py
class NameWorks(object):
def __init__(self, names):
self.names = names
def InputNames(self):
return self.names

Categories

Resources