-2

I have this python class with a method and a variable in it:

class Main:
    def do_something(self):
        #does something
        x = 'something'

Is there a way to access the x variable outside of the class?

Roy
  • 1,612
  • 2
  • 12
  • 38
  • 1
    No, like any other function, `x` is local to that function. It ceases to exist after the execution of the function (of course, the *object* being referred to by that variable may or may not cease to exist, depending on whether it's still being referenced somewhere else). If you need data from a function, you should *return* that data. Alternatively, if you are using a method in a class, you could set that object to some attribute. – juanpa.arrivillaga May 10 '20 at 04:43

1 Answers1

3

Yes there is, your existing code assigns 'something' to x, but this x is actually not associated with the class instance. Change x = 'something' to self.x = 'something' does the trick.

class Person:
    def do_something(self):
        self.x = 'something'

person = Person()
person.do_something()

print(person.x)
# Prints 'something'

Refer to this answer if you want to know more about the subtleties of initializing class variables.

tnwei
  • 860
  • 7
  • 15