gpt4 book ai didi

python - 如何检查对象是否已在python中初始化?

转载 作者:太空宇宙 更新时间:2023-11-04 03:02:46 25 4
gpt4 key购买 nike

如何检查一个对象是否已经在 python 中初始化?我在多个地方有 my_tac = tac(EDL_port) ,在它已经初始化的情况下它会抛出如下所示的错误..我想添加检查 my_tac 是否已初始化,该怎么做?代码:-

#From another file
my_tac = tac(EDL_port)

#alpha.py
class tac:
## tac class constructor.
#
# @param self
# @param timeout
# @param baud_rate
def __init__(self, port=None, timeout=0.3, baud_rate=115200):
if port is not None:
self.port = port
self.ser = serial.Serial(self.port, baud_rate, timeout=timeout)
return
else:
(tac_ports,spider_ports) = tac_probe_for_devices()
print "TAC ports..."
......................

错误:-

11/5/2016 8:54:05 PM: my_tac = tac(EDL_port)
11/5/2016 8:54:05 PM: File "C:\CST_QSPR\third_party_bin\BuildLoaderScripts\Android\android_dl\alpaca.py", line 90, in __init__
11/5/2016 8:54:05 PM: self.ser = serial.Serial(self.port, baud_rate, timeout=timeout)
11/5/2016 8:54:05 PM: File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 31, in __init__
11/5/2016 8:54:05 PM: ERROR:adb -s C2687475 remount failed
11/5/2016 8:54:05 PM: super(Serial, self).__init__(*args, **kwargs)
11/5/2016 8:54:05 PM: File "C:\Python27\lib\site-packages\serial\serialutil.py", line 236, in __init__
11/5/2016 8:54:05 PM: self.open()
11/5/2016 8:54:05 PM: File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 62, in open
11/5/2016 8:54:05 PM: raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
11/5/2016 8:54:05 PM: serial.serialutil.SerialException: could not open port 'COM8': WindowsError(5, 'Access is denied.')

最佳答案

OP 请求它,OP 接收它。这是单例模式的示例,仅分解为一个类。

class Test :
count = 0
def __init__(self, value) :
if self.__class__.count > 0 :
raise Exception
else :
self.__class__.count += 1
self.value = value #for the sake of the example


t1 = Test(12) #instantiates the object
t2 = Test(27) #throws an error

使用 Python 3.4.3 测试。

关于python - 如何检查对象是否已在python中初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40457599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com