如何检查一个对象是否已经在 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 测试。
