问题遇到的现象和发生背景
在编写外星人小游戏时遇到AttributeError: __enter__错误,不适用类函数就时正常的,但是已将with true放在类中就报错.AttributeError: enter,不知道是什么原因
```python
import sys
import pygame
from settings import Settings
class AlienInvasion:
"""管理游戏资源和行为的类"""
def __init__(self):
"""初始化游戏并创建游戏资源"""
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Alien Invasion")
def run_game(self):
"""开始游戏主循环"""
with True:
"""监视键盘和鼠标"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
"""让最近绘制的屏幕可见"""
self.screen.fill(self.settings.bg_color)
pygame.display.flip()
if __name__ == '__main__':
"""创建游戏实例并运行游戏."""
ai = AlienInvasion()
ai.run_game()
```python
pygame 2.1.0 (SDL 2.0.16, Python 3.10.0)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "D:\练习册\随手练习\外星人入侵游戏\alinen_invasion.py", line 31, in <module>
ai.run_game()
File "D:\练习册\随手练习\外星人入侵游戏\alinen_invasion.py", line 20, in run_game
with True:
AttributeError: __enter__