正在初始化 Python 个属性
Initialising Python properties
我正在编写 Python class 来使用 pyscopg2 管理 Postgres 数据库连接。
我希望 class 在初始化时建立与数据库的连接(我觉得这 可能 是个糟糕的主意,但我可以'想不出一个很好的理由)。我正在尝试使用我以前从未使用过的 属性 来完成这项工作。换句话说,我希望从 __init__
方法中调用 getter 。
我的 class 看起来像这样:
class MyDatabase:
connection_string = "host='<host_ip>' db_name='<db_name>'"
def __init__(self):
# *
self._connection = connection
@property
def connection(self):
# Check for an existing connection
if self._connection:
self._connection.close()
self._connection = psycopg2.connect(connection_string)
return self._connection
...
在此版本中,对现有连接的检查会抛出 AttributeError: Elefriends instance has no attribute '_connection'
,这是有道理的。我可以通过简单地在我用 # *
标记的地方添加一行 self._connection = None
来解决这个问题,但这感觉很笨拙。这是我为方便而付出的代价吗?我只是挑剔吗?或者有更好的方法吗?
谢谢!
代替 if ... 语句,您可以使用:
try:
self._connection.close()
except AttributeError:
pass
self._connection = psycopg2.connect(connection_string)
return self._connection
我正在编写 Python class 来使用 pyscopg2 管理 Postgres 数据库连接。
我希望 class 在初始化时建立与数据库的连接(我觉得这 可能 是个糟糕的主意,但我可以'想不出一个很好的理由)。我正在尝试使用我以前从未使用过的 属性 来完成这项工作。换句话说,我希望从 __init__
方法中调用 getter 。
我的 class 看起来像这样:
class MyDatabase:
connection_string = "host='<host_ip>' db_name='<db_name>'"
def __init__(self):
# *
self._connection = connection
@property
def connection(self):
# Check for an existing connection
if self._connection:
self._connection.close()
self._connection = psycopg2.connect(connection_string)
return self._connection
...
在此版本中,对现有连接的检查会抛出 AttributeError: Elefriends instance has no attribute '_connection'
,这是有道理的。我可以通过简单地在我用 # *
标记的地方添加一行 self._connection = None
来解决这个问题,但这感觉很笨拙。这是我为方便而付出的代价吗?我只是挑剔吗?或者有更好的方法吗?
谢谢!
代替 if ... 语句,您可以使用:
try:
self._connection.close()
except AttributeError:
pass
self._connection = psycopg2.connect(connection_string)
return self._connection