Python - Using variable outside and inside the class and method

Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.

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.


# defined outside the class'
# Variable defined outside the class.
outVar = 'outside_class'    
print("Outside_class1", outVar)
''' Class one '''
class Ctest:
   print("Outside_class2", outVar)
   def access_method(self):
      print("Outside_class3", outVar)
# Calling method by creating object
uac = Ctest()
''' Class two '''
class Another_ Ctest_class:
   print("Outside_class4", outVar)
   def another_access_method(self):
      print("Outside_class5", outVar)
# Calling method by creating object
uaac = Another_ Ctest_class()
The variables that are defined inside the methods can be accessed within that method only by simply using the variable name.
# defined inside the method'
'''class one'''
class Ctest:
   def access_method(self):
      # Variable defined inside the method.
      inVar = 'inside_method'
      print("Inside_method3", inVar)
uac = Ctest()
'''class two'''
class AnotherCtest:
   def access_method(self):
uaac = AnotherCtest()

Updated on: 06-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started