尝试将其他属性分配给变量时"AttributeError: 'str' has no attribute"



我在Python 3:中运行此代码时遇到此错误

class Game:
def __init__(self):
self.status = "runing"
self.display = "window1"
self.display.window = "None"
self.display.window.width = 1920
self.display.window.height = 1080
self.display.window.name = "Space Shooter Game"
self.display.fps = 30
game = Game()

错误消息:

File "test.py", line 12, in <module>
game = Game()
File "test.py", line 5, in __init__
self.display.window = "None"
AttributeError: 'str' object has no attribute 'window'

我该怎么解决这个问题?

多层变量在python中不可用:用self.display.window = "None"代替self.display_window = "None"

字典可用于多层属性

class Game:
def __init__(self):
self.status = "runing"
self.display = dict()
self.display["window"] = dict()
self.display["window"]["width"] = 1920
self.display["window"]["height"] = 1080
self.display["window"]["name"] = "Space Shooter Game"
self.display["fps"] = 30

game = Game()

相关内容

最新更新