Can you access a variable inside a function python?


Global Variables

Variables that are created outside of a function (as in all of the examples above) are known as global variables.

Global variables can be used by everyone, both inside of functions and outside.

Example

Create a variable outside of a function, and use it inside the function

x = "awesome"

def myfunc():
  print("Python is " + x)

myfunc()

Try it Yourself »

If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

Example

Create a variable inside a function, with the same name as the global variable

x = "awesome"

def myfunc():
  x = "fantastic"
  print("Python is " + x)

myfunc()

print("Python is " + x)

Try it Yourself »



The global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.

To create a global variable inside a function, you can use the global keyword.

Example

If you use the global keyword, the variable belongs to the global scope:

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Try it Yourself »

Also, use the global keyword if you want to change a global variable inside a function.

Example

To change the value of a global variable inside a function, refer to the variable by using the global keyword:

x = "awesome"

def myfunc():
  global x
  x = "fantastic"

myfunc()

print("Python is " + x)

Try it Yourself »



If you want to avoid global, one possible approach is to define a class. Each class instance has its own attributes; there is also a class attribute space where instances can share an attribute between them.

Object-oriented programming can be challenging to get into if you are new to Python, but this might actually be a good time to start playing with it.

class Thing:
    shared = "foo"

    def __init__(self):
        """
        This gets called when you create a new Thing()
        """
        self.bar = "baz"  # default value for new instances

    def get_bar(self):
        return self.bar

    def set_bar(self, value):
        self.bar = value

Now, let's create two instances.

first = Thing()
second = Thing()

The get_bar and set_bar methods are not strictly necessary in simple examples like this one. You can also do

second.bar = "ick"
print(second.bar)
# "ick"
print(first.bar)
# "baz"

(though for more complex scenarios, you probably want to require users to call the setter and getter methods; there are ways to force this - see e.g. What's the pythonic way to use getters and setters?)

If you change a class attribute via one instance, it will not be changed in the other instances, either.

second.shared = "poo"
print(first.shared)
# "foo"

But if you change it in the class itself, it will be changed in all the instances which have not separately overridden the shared value.

Thing.shared = "zoom"
print(first.shared)
# "zoom"
print(second.shared)
# "poo", still

To recap, you create a new Thing instance by calling Thing(); this will run the __init__ method before returning the new instance. Inside the class, the instance is the first argument to every (non-static, non-class) method, and conventionally called self (though you could get away with calling it shirley if you wanted to, as far as the Python interpreter is concerned).

There's a lot more to classes; the main selling point is probably that you can create subclasses which inherit from their parent class but can override some behaviors (common examples often involve real-world concepts like animals or vehicles, but a class can just be anything where you want to create a type and encapsulate its behavior, and perhaps override some methods in derived types).

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In Python, we can define the variable outside the class, inside the class, and even inside the methods. Let’s see, how to use and access these variables throughout the program.

    Variable defined outside the class:

    The variables that are defined outside the class can be accessed by any class or any methods in the class by just writing the variable name.

    outVar = 'outside_class'    

    print("Outside_class1", outVar)

    class Geek:

        print("Outside_class2", outVar)

        def access_method(self):

            print("Outside_class3", outVar)

    uac = Geek()

    uac.access_method()

    class Another_Geek_class:

        print("Outside_class4", outVar) 

        def another_access_method(self):

            print("Outside_class5", outVar)

    uaac = Another_Geek_class()

    uaac.another_access_method()

    Output:

    Outside_class1 outside_class
    Outside_class2 outside_class
    Outside_class3 outside_class
    Outside_class4 outside_class
    Outside_class5 outside_class
    

     
    Variable defined inside the class:

    The variables that are defined inside the class but outside the method can be accessed within the class(all methods included) using the instance of a class. For Example – self.var_name.
    If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.

    class Geek:

        inVar = 'inside_class'

        print("Inside_class2", inVar)

        def access_method(self):

            print("Inside_class3", self.inVar)

    uac = Geek()

    uac.access_method()

    class another_Geek_class:

        print()

        def another_access_method(self):

            print()

    uaac = another_Geek_class()

    uaac.another_access_method()

    Output:

    Inside_class2 inside_class
    Inside_class3 inside_class
    

    The statements which are marked as error will produce an error upon execution as the variable is not accessible there.

     
    Variable defined inside the method:

    The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name.
    If you want to use that variable outside the method or class, you have to declared that variable as a global.

    class Geek:

        print()

        def access_method(self):

            inVar = 'inside_method'

            print("Inside_method3", inVar)

    uac = Geek()

    uac.access_method()

    class AnotherGeek:

        print()

        def access_method(self):

            print()

    uaac = AnotherGeek()

    uaac.access_method()

    Output:

    Inside_method3 inside_method
    

    The statements which are marked as error will produce error upon execution as the variable is not accessible there.

    Summary:

    Can you access a variable inside a function python?


    Can you access variables inside a function?

    In other words, variables that are declared outside of a function are known as global variables. You can access global variables in Python both inside and outside the function.

    How do you call a variable inside a function in Python?

    Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.

    How do you access the class variable inside a function in Python?

    Use class_name. variable_name to access a class variable from a class method. Use class_name. variable_name to access a class variable with variable_name of class class_name from a class method.

    Can you access the variables defined inside a function outside its body in Python?

    In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.