python - Traceback 类未定义
问题描述
我有一个正在进行的项目,它引用了其他类中的几个类。
代码:
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
当我创建 app() 类的实例时,我得到一个回溯:
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
我曾尝试将 pinIn 和 pinout 类移入门类,然后将它们全部移入 app 类,但这些都不起作用。在此之前,我一直将 _in 声明为包含两个 pinIn 实例的列表,但遇到了同样的错误。
为什么门类看不到 pinIn 和 pinout 类?
解决方案
该类pinOut
是在您引用它之后定义的:
class gate():
gateType = 'none'
_in = []
_out = pinOut() # referenced here
...
class pinOut(): # defined here
...
将 的定义移到 ofpinOut
之前,gate
或者更好的是,将其设置为__init__
:
class gate():
gateType = 'none'
def __init__(self):
self._in = [pinIn(), pinIn()]
self._out = pinOut()
您应该更喜欢初始化事物的原因__init__
是这样可以避免在多个实例之间共享状态,这很可能是您想要避免的。
推荐阅读
- javascript - 如何在Angular 6中使用反应式表单隐藏字段后提交表单?
- .net - 在 Winform 应用程序中使用 Matlab 生成的 .Net 程序集
- php - jQuery 中的 bloginfo('template_directory') 用于管理面板
- ecmascript-6 - 使用 Node Rollup 如何生成 ES2015 输出
- html - 引导工具提示
- jquery - 如何防止 JQuery 中的第二次点击?
- sql - 我可以在外键列中添加非原子值吗?
- javascript - 将所有访问者浏览器信息保存到会话中不起作用
- python - NameError: __file__ 未定义
- cakephp-3.0 - 如果满足条件,如何初始化数据库中的表对象?蛋糕PHP