1

I've made a class with some variables being set in the ___init____ and I want to be able to change these variables from methods in that class ie.

class example_class:

    def __init__(self, variable):
        self.thing = 'variable'

    def example_method(self):
        self.thing = 'changed text'

    def different_method(self):
        print(self.thing)

So before calling "example_method" the value of self.thing is the string 'variable' and then after calling the method "example_method" self.thing now equals 'changed text'. This must be possible but I don't understand how to do it

2
  • What problem are you actually seeing with your implementation? Commented Dec 7, 2017 at 9:47
  • After running the method example_method the value of self.thing is still the original string 'variable' it hasn't changed to 'changed text' Commented Dec 7, 2017 at 10:11

1 Answer 1

1

You must call the method you've defined into the class to happen.

class example_class:

    def __init__(self, variable):
        self.thing = 'variable'
        self.example_method()

    def example_method(self):
        self.thing = 'changed text'

    def different_method(self):

In this way, when you get/create an instance of the class "example_class", the method "example_method" will be called in the constructor.

You could also do something like:

if __name__ == '__main__':
    my_class = example_class()
    my_class.example_method()
Sign up to request clarification or add additional context in comments.

4 Comments

I realise I haven't but the code in my post but I do call the method I just don't want to call it in the init. I want to construct the instance of the class and then later be able to call "example_method" to change the variable self.thing
you don't need to call the method inside the init method if you won't. But as i said in my previous post, you want something similar to the last 3 rows of code. You need an instance of that class and after you can easily call the method you want from it.
Yeah I have created an instance of the class and then call the method but the string still doesn't change
Then you're doing something wrong, please post the code.

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.