简体   繁体   中英

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'

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM