Home > OS >  Python, self.alpha = alpha ran in function, but not found when calling self.alpha in its class
Python, self.alpha = alpha ran in function, but not found when calling self.alpha in its class

Time:03-06

This is pretty weird since I have no idea what should I call this error.

So basically, I'm trying to input the file from another module

file1 (Input)

from file2 import Module2   

class Module1():
    def app_name(self,name):
        p = Module2()
        p.app_name(name)

    def app_directory(self,directory):
        p = Module2()
        p.app_directory(directory)
        
m = Module1()
m.app_name("app")
m.app_directory("path/to/app")

file2 (getting)

class Module2():
    def __init__(self):
        self.name = None
        self.directory = None
        
    def app_name(self,name):
        self.name = name
        
    def app_directory(self,directory):
        self.directory = directory
        self.pr()
    
    def pr(self):
        print(self.name,self.directory)

After being executed, It gave me self.name = None just like what it is in init, but self.directory is what I typed in. I spent hours but still can't figure out what is the problem, I really need help.

CodePudding user response:

I think this is pretty normal, you are not keeping track of p created in Module1 app_name, In other words, you are creating 2 separate objects:

If you want p you should do this:

from file2 import Module2   

class Module1():
    def app_name(self,name):
        self.p =Module2()
        self.p.app_name(name)

    def app_directory(self,directory):
        # p = Module2()
        self.p.app_directory(directory)
        
m = Module1()
m.app_name("app")
m.app_directory("path/to/app")

return :

app path/to/app
  • Related