0

I'm new in python, and I have this code:

class Daemon():        
    db = Database()

    def __init__(self):        
        final_folder = ''

How I can change the value of the variable final_folder in the same class but in other function?

I try the code like below but isn't work:

class Daemon():    
    db = Database()

    def __init__(self):
        final_folder = ''

    def get_mail_body(self, msg):
        Daemon.final_folder = 'someotherstring'
1
  • 1
    final_folder is a local variable that ceases to exist once __init__ is done executing. You likely want to use an instance variable, in which case, you need to explicitely use self.final_folder = '' then access it with self.final_folder in other methods. Commented Jan 23, 2018 at 17:47

2 Answers 2

1

You need to refer to it as self.final_folder in __init__, like:

class Daemon():

    db = Database()

    def __init__(self):

        self.final_folder = ''

    def get_mail_body(self, msg):

        self.final_folder = 'someotherstring'

Then you should be able to do something like:

my_daemon = Daemon()
print(my_daemon.final_folder)
# outputs: ''
my_daemon.get_mail_body('fake message')
print(my_daemon.final_folder)
# outputs: 'someotherstring'
Sign up to request clarification or add additional context in comments.

Comments

0

you need to access the variable with self if you are using inside the class. self holds the current object.

Here is the updated code.

def __init__(self):
   self.final_folder = ''
def get_mail_body(self)
    self.final_folder = 'Hello'

Create the object of the class and access the variable.

2 Comments

I need to change value of the final_folder, if the function is within the class it doesn't change the value
Is this not the same solution that I posted? If you think it's different, can you edit clarify the difference / improvement?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.