Python Forum
How can import variable beteen classes in same module - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: How can import variable beteen classes in same module (/thread-26023.html)



How can import variable beteen classes in same module - johnjh - Apr-18-2020

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



RE: How can import variable beteen classes in same module - deanhystad - Apr-19-2020

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)