Gustavo Piris
Gustavo Piris

Reputation: 68

How change value of variable in same class?

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'

Upvotes: 0

Views: 55

Answers (2)

Onkar Kundargi
Onkar Kundargi

Reputation: 1

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.

Upvotes: 0

user
user

Reputation: 4811

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'

Upvotes: 1

Related Questions