Python Forum
access variables between classes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
access variables between classes
#1
Hi I am new to python and have been trying to develop a tkinter application. My question is, how can you use a variable from a class method to another class method? I have tried global and it doesnt work and keep showing error that the name is not found.

Example

class Page1(tk.frame)

def A(self)
global left
#assess csv file for a value and assign to variable left
left=row[2]
...

class Page2(tk.frame)
...
def B(self)
self.x= left
...

When compile, Error is shown as left is not defined. I am also unable to create instances for Page1 and Page2 as the main application runs in the manner below,

app=Mainclass()
app.mainloop()

Class Page1 and Page2 are fired from app object (instance of Mainclass)
Reply
#2
In future posts:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Thanks
  • You have no ':' at end of def.
  • the body of your functions are not indented
  • Though not specifically required, you have no init method for your classes
  • Please show full error traceback, and only run-able code snippets
Reply
#3
Use inheritance. Make left a class attribute of mainclass,and subclass page1 and 2
Recommended Tutorials:
Reply
#4
(Jan-28-2018, 06:24 PM)metulburr Wrote: Use inheritance. Make left a class attribute of mainclass,and subclass page1 and 2

Can u please provide a sample code to fix this problem as i am facing a similar problem
Reply
#5
class Child():
  def __init__(self):
    self.var_2 = "World"

class Main():
  def __init__(self):
    self.var_1 = "Hello"
    self.child = Child()
    print("Inside class:", self.var_1, self.child.var_2)

main = Main()
print("Outside class:", main.var_1, main.child.var_2)
Reply


Forum Jump:

User Panel Messages

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