Python Forum
How can import variable beteen classes in same module
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can import variable beteen classes in same module
#1
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
Reply
#2
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to import entire module ? tonycstech 5 997 Oct-21-2020, 06:16 AM
Last Post: tonycstech
  Scope of variable when using two classes AyJay 2 500 Jan-23-2020, 10:09 AM
Last Post: AyJay
  How to share a variable between two Python classes? robin1992 2 821 Nov-27-2019, 09:42 AM
Last Post: robin1992
  [Tkinter] need help using a returned value to import module Brave774 16 3,343 Jun-01-2018, 08:03 AM
Last Post: Brave774

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020