Home > Software engineering >  python get new value in a class or method
python get new value in a class or method

Time:05-15

i'am new to python and try to get the new value for my bool in a class .

i try create a global, set in the init.

How can i get the new value of the test bool in getnewvalue() ?

Here is my code :

test = False

class myclass():
   def changevalue()
       test = True
       getnewvalue()

   def getnewvalue():
       print(test) 

CodePudding user response:

If you want to have data inside your class, it's a good idea to use the __init__() and save it like that. More here in the Python tutorial: Class Objects.

And use the __init__ to initialize the class with desired values. Your code should look something like this:

test = False

class myclass():

    def __init__(self, test):
        self.test = test  # self keyword is used to access/set attrs of the class
        # __init__() gets called when the object is created, if you want to call
        # any function on the creation of the object after setting the values
        # you can do it here
        self.changevalue()

    def changevalue(self):  # if you want to access the values of the class you
                            # need to pass self as a argument to the function 
        self.test = not test
        self.getnewvalue()

    def getnewvalue(self):
        print(self.test)  # use self to access objects test value

_class = myclass(False)

Or if you just want to have a class with functions, you can do something like this:

test = False

class myclass():
    @staticmethod
    def changevalue(val)
        return not val

    def getnewvalue():
        print(test)

_class = myclass()
test = _class.changevalue(test)

This way it won't print your value on call because it's just setting your value to return of that function. You'll have to do it yourself but that shouldn't be a problem. More about staticmethods here: @staticmethod

CodePudding user response:

Add

global test

to both functions. The resulting code would be...

test = False

class myclass():
   def changevalue():
       global test
       test = True
       getnewvalue()

   def getnewvalue():
       global test
       print(test)

global allows the function to access variables outside of itself. Hope this helps!

  • Related