After looking through many posts of class variables and instance variables I am not understanding how to share variables among classes.
#!/usr/bin/python3
from PyQt5.QtWidgets import (QApplication)
import sys
class One():
def __init__(self, myTextString, parent=None):
self.mytext = myTextString
self.printtxt()
Main.txt = 'another string'
self.txt2 = 'a third string'
def printtxt(self):
print('One',self.mytext)
class Two():
def __init__(self, parent=None):
self.printtxt()
def printtxt(self):
print('Two',One.txt) # Attribute Error
print('Two',One.txt2) # Attribute Error
class Main():
def __init__(self, parent = None):
self.txt = 'a string of text'
self.w = One(self.txt)
self.w1 = Two()
print(self.txt) # not changed by One
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Main()
sys.exit(app.exec_())
In the above code the Main class initiates class One and class Two. While I can send the value of self.txt to the initiated class One, there are two problems I am having.
- When I try to print One’s variables in class Two’s printtxt I get attribute errors:
AttributeError: type object ‘One’ has no attribute ‘mytext’
AttributeError: type object ‘One’ has no attribute ‘txt2’
- When I try and change Main’s txt variable in One, it is not changed
I would like to share a value created in any particular class with all the other classes that are created (in other words ‘global’ variables up to a point).
The controller concept in Bryan Oakley’s Tkinter example (see Switch between two frames in tkinter? and How to get variable data from a class?) is close I think, but if anyone can answer or point me to posts that explain this simply, I’d be grateful.
Thank you for any help.