Python Forum

Full Version: How can import variable beteen classes in same module
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need to import this path variable from first class to another classes, this is my code:

import openpyxl

class Excell():
      global path
      def send_message(self, data):
          global path
          print("Path Excel is : '{}'".format(data))
          path = data # I need to export this variable 'path' to class First()
 
class First():
      global path
      wb = openpyxl.load_workbook(path)
      sheet = wb['sheet']
      firstCell= sheet["A1"].value
      print("Cell is :" + firstCell)
After run code, I see this message:

Error:
C:\Python\python.exe E:/PycharmProjects/test/firstTest.py Traceback (most recent call last): File "E:\PycharmProjects\test\firstTest.py", line 11, in <module> class First(): File "E:\PycharmProjects\test\firstTest.py", line 13, in First wb = openpyxl.load_workbook(path) NameError: name 'path' is not defined Process finished with exit code 1
Use a class variable. You kind of almost have this except you need to leave of the "global".
class Excell():
      path = ""  # This is a class varaible
      def send_message(self, data):
          print("Path Excel is : '{}'".format(data))
          self.path = data # Assigning value to Excell.path class variable
  
class First():
      wb = openpyxl.load_workbook(Excell.path) # Using the class variable outside the class
      sheet = wb['sheet']
      firstCell= sheet["A1"].value
      print("Cell is :" + firstCell)