Home > OS >  How to access variable from function from another function in a class
How to access variable from function from another function in a class

Time:05-11

I need to access a variable from a function inside another function in the same class. If I call both functions outside the class, it works. However; if I only call the second function that relies on a variable defined in the first function it returns None. How do I go about doing this, so I don't have to call both functions?

CodePudding user response:

Simple answer: You cant.
Long answer: You cant Access local variables outside their scope. Each function has its own scope, therefore it cannot be accessed from outside. But you can do something like this:

my_val = 0 # is now global
def my_fun():
    global my_val
    # some Code here

With the global Keyword, you can refer to variables, that have been declared in global scope. Normaly, you can access any globaly defined variable, but if you reasign it inside an function, it needs to be loaded first with global my_val..

CodePudding user response:

I guess you can use the fact that variables are pointers in python,

It simply depends on the problem, since we don't have much details

class A:
  def __init__(self):
    matrix = [[0, 0], [0, 0]]
    self.initmatrix(matrix)
    print(matrix)

  def initmatrix(self, m):
    m[0][0] = 1


myObj = A()

prints [[1, 0][0, 0]]

  • Related