Class 变量为 NoneType,即使属性已定义
Class variable is NoneType even though attribute was defined
我有一个 class 看起来像这样:
class DatabaseTest:
def __init__(self):
self.headers = {
"host": os.environ["HOST"],
"username": os.environ["USERNAME"],
"password": os.environ["PASSWORD"]
}
self.db = None
self.cursor = None
asyncio.create_task(self._connect())
async def _connect(self):
self.db = await aiomysql.connect(self.headers['host'], self.headers['username'], self.headers['password'])
self.cursor = await self.db.cursor()
await self.cursor.execute('use bot')
async def _insertData(self, guildid):
sql = f'insert into data(guild) values ({guildid})'
await self.cursor.execute(sql)
每当我执行 await DatabaseTest()._insertData(123456789)
时,它都会给出一个错误,指出 self.cursor 是 NoneType 当我清楚地重新定义了 _connect 中的 self.cursor 时。我知道 _connect 被调用是因为我在最后放了一个 print 语句并且它被打印出来了。我该如何解决这个问题?
回溯是这样的(我将它用于不和谐的机器人):
Traceback (most recent call last):
File "C:\Users\Name\PycharmProjects\compscibot\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Name\PycharmProjects\compscibot\cogs\startup\Help.py", line 57, in cmdchannel
channelid = await DatabaseTest().getData(ctx.guild.id,'cmdchannel')
File "C:\Users\Name\PycharmProjects\compscibot\cogs\dbtest.py", line 75, in getData
await self.cursor.execute(sql)
AttributeError: 'NoneType' object has no attribute 'execute'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Name\PycharmProjects\compscibot\venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Name\PycharmProjects\compscibot\venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Name\PycharmProjects\compscibot\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'execute'
None
直到 await
才切换上下文。
asyncio.create_task()
只是 安排 执行。
使用asyncio.sleep()
:
db = DatabaseTest()
await asyncio.sleep(0)
db._insertData(123456789)
或重构:
class DatabaseTest:
def __init__(self):
self.headers = {
"host": os.environ["HOST"],
"username": os.environ["USERNAME"],
"password": os.environ["PASSWORD"]
}
async def __aenter__(self):
await self._connect()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
# cleanup
await self.cursor.close()
self.db.close()
...
async with DatabaseTest() as db:
await db._insertData(123456789)
我有一个 class 看起来像这样:
class DatabaseTest:
def __init__(self):
self.headers = {
"host": os.environ["HOST"],
"username": os.environ["USERNAME"],
"password": os.environ["PASSWORD"]
}
self.db = None
self.cursor = None
asyncio.create_task(self._connect())
async def _connect(self):
self.db = await aiomysql.connect(self.headers['host'], self.headers['username'], self.headers['password'])
self.cursor = await self.db.cursor()
await self.cursor.execute('use bot')
async def _insertData(self, guildid):
sql = f'insert into data(guild) values ({guildid})'
await self.cursor.execute(sql)
每当我执行 await DatabaseTest()._insertData(123456789)
时,它都会给出一个错误,指出 self.cursor 是 NoneType 当我清楚地重新定义了 _connect 中的 self.cursor 时。我知道 _connect 被调用是因为我在最后放了一个 print 语句并且它被打印出来了。我该如何解决这个问题?
回溯是这样的(我将它用于不和谐的机器人):
Traceback (most recent call last):
File "C:\Users\Name\PycharmProjects\compscibot\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Name\PycharmProjects\compscibot\cogs\startup\Help.py", line 57, in cmdchannel
channelid = await DatabaseTest().getData(ctx.guild.id,'cmdchannel')
File "C:\Users\Name\PycharmProjects\compscibot\cogs\dbtest.py", line 75, in getData
await self.cursor.execute(sql)
AttributeError: 'NoneType' object has no attribute 'execute'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Name\PycharmProjects\compscibot\venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Name\PycharmProjects\compscibot\venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Name\PycharmProjects\compscibot\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'execute'
None
直到 await
才切换上下文。
asyncio.create_task()
只是 安排 执行。
使用asyncio.sleep()
:
db = DatabaseTest()
await asyncio.sleep(0)
db._insertData(123456789)
或重构:
class DatabaseTest:
def __init__(self):
self.headers = {
"host": os.environ["HOST"],
"username": os.environ["USERNAME"],
"password": os.environ["PASSWORD"]
}
async def __aenter__(self):
await self._connect()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
# cleanup
await self.cursor.close()
self.db.close()
...
async with DatabaseTest() as db:
await db._insertData(123456789)