Reputation: 481
I have a project in progress which references several classes from within other classes.
code:
try:
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
except:
input('Please install PyQt5 before using the GUI system. (press enter to close)')
exit()
class app(QApplication):
def __init__(self):
super(app, self).__init__([])
print('running')
andGate = gate()
andGate.config('and', 2)
def initUI(self):
newAndBtn = QPushButton(self)
newOrBtn = QPushButton(self)
newXorBtn = QPushButton(self)
def newAndGate(self):
pass
class gate():
gateType = 'none'
_in = []
_out = pinOut()
def _init__(self):
_in.append(pinIn())
_in.append(pinIn())
pass
def config(self, gateType, inputTargets):
#just some safety checks
if gateType not in supportedGates:
return False
self.gateType = gateType
if type(inputTargets) is not list:
return False
for i in inputTargets:
if type(i) is not pinOut:
return False
self.gateType = gateType
for i in range(len(self._in)):
self._in[i].point(inputTargets[i])
def update(self):
if _in[0].fetch() and _in[1].fetch():
_out.set(True)
else:
_out.set(False)
print("update for {}".format(self))
class pinIn():
value = True
reference = None
def __init__(self):
pass
def point(target):
if type(target) is not connOut:
return False
reference = target
def fetch():
self.value = reference.value
return self.value
class pinOut():
value = False
def __init__(self):
pass
def set(self, newValue):
if type(newValue) is not bool:
return False
self.value = newValue
when I create an instance of the app() class, I get a traceback:
Traceback (most recent call last):
File "C:\Users\ccronk22\Documents\Python_Scripts\Logic\run.py", line 1, in <module>
import main
File "C:\Users\ccronk22\Documents\Python_Scripts\Logic\main.py", line 8, in <module>
class app(QApplication):
File "C:\Users\ccronk22\Documents\Python_Scripts\Logic\main.py", line 23, in app
class gate():
File "C:\Users\ccronk22\Documents\Python_Scripts\Logic\main.py", line 26, in gate
output = pinOut()
NameError: name 'pinOut' is not defined
I have tried moving the pinIn and pinout classes into the gate class, then moving them all into the app class, but none of this works. Before this, I had been declaring _in as a list containing two pinIn instances, but was getting the same error.
Why can't the gate class see the pinIn and pinout classes?
Upvotes: 0
Views: 258
Reputation: 17751
The class pinOut
is defined after you reference it:
class gate():
gateType = 'none'
_in = []
_out = pinOut() # referenced here
...
class pinOut(): # defined here
...
Either move the definition of pinOut
before the one of gate
or, even better, set it in __init__
:
class gate():
gateType = 'none'
def __init__(self):
self._in = [pinIn(), pinIn()]
self._out = pinOut()
The reason why you should prefer initializing things in __init__
is that this avoids sharing state between multiple instances, which is most likely what you want to avoid.
Upvotes: 1