1

I am trying to access an updated initialized variable by a python method to another python method in same class. Below is my sample code block.

class test(object):
    def __init__(self):
        self.a = []

    def test1(self):
        self.a = [1,2,3,4,5]
        print ("Output of test1 #", self.a)

    def test2(self):
        print ("Output of test2 #",self.a)
test().test1()
test().test2()

Output # Output of test1 # [1, 2, 3, 4, 5]
         Output of test2 # []

My understanding is if i Initialize a variable in __ init __(self) section then i can update the same variable from a method in the class and access the same variable from another method of same class. Correct me if my understanding is wrong.

2
  • "access the same variable from another module of same class.". Do you mean "access the same variable from another instance of same class." Or am I misunderstanding what you mean. Commented Apr 15, 2016 at 6:05
  • 1
    Here, however, you're creating two different instances of test. Instead: t = test(); t.test1(); t.test2() does what you want. You may want up a bit more on (Python) classes. Commented Apr 15, 2016 at 6:06

2 Answers 2

4

Instead of module, the word you want is method.

Your understanding is correct, but only for the same instance -- and you are creating two instances:

test().test1()
# ^- just created a new instance of test
test().test2()
# ^- just created another, different instance of test

What you want instead:

test_instance = test()
test_instance.test1()
test_instance.test2()
Sign up to request clarification or add additional context in comments.

Comments

0

Because of test().test1() and test().test2() are two difference object. I think you should read more about Python OPP : https://docs.python.org/2/tutorial/classes.html

Comments

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.