'"AttributeError: 'str' has no attribute" when trying to assign additional attributes to variable
I am getting this error when running this code in 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()
Error message:
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'
How can I fix this?
Solution 1:[1]
Multi layer variable are not available in python : self.display.window = "None" do instead self.display_window = "None"
Solution 2:[2]
Dictionary can be used for muli-layer attributes
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Max Chaos |
| Solution 2 | Mazhar |
