python - How do I make a variable in a module on a global namespace? -


i have been working on module takes file name , file line , creates variable defined user , works. want variable on global namespace here code:

def int(file, line, variable):     file = open(file, "r")     in range(line):         whattoconvert = file.readline()     file.close     globals()[variable] = int(whattoconvert)  def str(file, line, variable):         file = open(file, "r")         in range(line):             whattoconvert = file.readline()         file.close         globals()[variable] = str(whattoconvert)  def float(file, line, variable):         file = open(file, "r")         in range(line):             whattoconvert = file.readline()         file.close         globals()[variable] = float(whattoconvert) 

if import convert convert.int("test.txt", 1, "var_1") var ("var_1") accessible convert.var_1 not var_1 how can make var_1 on global namespace?

you want class, bro.

class converter:      def __init__(self, fl, ln, vrbl):         self.file = fl         self.line = ln         self.variable = vrbl       def to_int(self):         file = open(self.file, "r")         in range(self.line):             whattoconvert = file.readline()         file.close         return int(whattoconvert)      def to_str(self):         file = open(self.file, "r")         in range(self.line):             whattoconvert = file.readline()         file.close         return str(whattoconvert)      def to_float(self):         file = open(self.file, "r")         in range(self.line):             whattoconvert = file.readline()         file.close         return float(whattoconvert)   #instantiation foo = converter('\a\path','an int?','')  #this how call class methods. foo.to_int() foo.to_str() foo.to_float() 

i don't know input supposed like, can want this. , can store class definitions in other files , import them modules.

from filename import converter

then instantiate, etc., wrote. might change of envisioned program, might make easier too.

the __init__() function happens on line foo = converter('\a\path','an int?','') may want think putting open statement there , saving values in variables names self.variable. anywhere in class can make reference self.variable. notice self first argument of every method definition. self means object itself. there may many ways make class want.


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -