如何检查某个对象是否已在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.')
答案 0 :(得分:1)
您在这里看到的是Singleton设计模式。这种方法的关键思想是对象只能实例化一次。第二次尝试实例化它时,您将获得相同的对象。它可以像您的情况一样方便地访问数据库或创建端口句柄。没有真正的方法可以在python中使单例出类。但是,您可以将类转换为模块tac.py
。 python中的模块默认是单例。对于初始化,您可以定义init(port=None, timeout=0.3, baud_rate=115200)
函数,该函数将采用任何必需的参数。
# tac.py
port = None
def init(myport=None, timeout=0.3, baud_rate=115200):
if myport is not None:
global port
port = myport
ser = serial.Serial(port, baud_rate, timeout=timeout)
return
else:
tac_ports, spider_ports = tac_probe_for_devices()
print "TAC ports..."
def tac_probe_for_devices():
# Probe some devices
pass
import tac
tac.init(8080)
# From another file
import tac
print 'Tac port: ', tac.port # Print 8080
请查看this帖子了解更多实施细节。
答案 1 :(得分:1)
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进行测试。
答案 2 :(得分:0)
有多种方法可以解决这个问题。但是,我相信Singleton design pattern
是解决这个问题最优雅的方法。
有关信息。关于如何实现Singleton设计模式,请参考以下
答案 3 :(得分:0)
这是设置单例类并将端口传递给它的方法。只需从SingletonClass继承你的tac类。这里有一个技巧,以确保您不会两次致电__init__
。看看我如何检查super(self.__class__, self).__init__()
的返回以确保它没有发生。
# tac.py
class SingletonClass(object):
_inst = None
_init_called = False
def __new__(typ, *args, **kwargs):
if SingletonClass._inst is None:
obj = object.__new__(typ, *args, **kwargs)
SingletonClass._inst = obj
return SingletonClass._inst
def __init__(self):
# Call init inly on first instantiation if this class
if SingletonClass._init_called:
return True
SingletonClass._init_called = True
class MyClass(SingletonClass):
def __init__(self, port):
if super(self.__class__, self).__init__():
return
self._port = port
self._connections = '[D] Connection on port: %s' % self._port
def connection(self):
return self._connections
# From another file
from tac import MyClass
con = MyClass(8080)
print 'First connection id: ', id(con)
print con.connection()
con = MyClass(5000)
print 'Second connection id: ', id(con)
print con.connection()