AttributeError: type object has no attribute (problem with *args?)

AttributeError: type object has no attribute (problem with *args?)

注意:这不是 的副本。 我正在尝试编写文本冒险。

class place(object):
    def __init__(self):
        super(place, self).__init__()
        self.directions = {
            "N":None,
            "S":None,
            "E":None,
            "W":None,
            "NE":None,
            "NW":None,
            "SE":None,
            "SW":None
        }


    def add_directions(self, *args): #There's a problem with putting *args because it takes self as string
        #I'm sure there is a more elegant way to do this
        for direction in args:
            for key in self.directions:
                self.directions[key] = direction
        print(self)

place()
place.add_directions(place, "The Dark Room")

我想将 "The Dark Room" 添加到 class 变量 "self.directions"。但是,每当我这样做时,他们都会给出这个错误:

"C:\Program Files (x86)\Python38-32\python.exe" "C:/Users/samue/Documents/School/Y3 2020/Computer Science/Python/TextAdventure/The Dark Asylum.py"
Traceback (most recent call last):
  File "C:/Users/samue/Documents/School/Y3 2020/Computer Science/Python/TextAdventure/The Dark Asylum.py", line 25, in <module>
    place.add_directions(place, "No")
  File "C:/Users/samue/Documents/School/Y3 2020/Computer Science/Python/TextAdventure/The Dark Asylum.py", line 20, in add_directions
    for key in self.directions:
AttributeError: type object 'place' has no attribute 'directions'

我知道我对对象的理解不是很好,但是有人可以帮助我在 string 中为 class 变量中的每个键分配单独的方向 self.directions?是不是函数add_directions中的*args有问题?

问题出在你的最后两行:

place()
place.add_directions(place, "The Dark Room")

应该是:

p = place()
p.add_directions("The Dark Room")

您正在调用 place 构造函数,但没有在任何地方分配它。您不需要为 self 传递 placep.add_directions 中的 p 部分自动为 self.

您需要创建 class 地点的实例。 place() - 是 class 地点的实例,place - class 本身。你也不需要为自己传递参数。它会自动通过。你的代码应该是

p = place()
p.add_directions("The Dark Room")

P.S.By 约定 class

的首字母大写

place.add_directions(place, "The Dark Room") 在这一行中,您引用的是 class 地点,而不是 class、

地点的实例

在python和其他面向对象的编程语言中,您首先需要在访问其成员之前实例化或初始化一个class。

place_instance = place()
place_instance.add_directions("The Dark Room")

没有必要像您所做的那样将class作为self传递,self需要定义方法,而不是在调用方法时。

为了使这段代码更具可读性,请考虑使用大写字母来表示位置。可以写成class Place()

在使用该变量(作为实例)之前,您必须将 place() 分配给变量(使其成为实例)。这就是为什么所有答案都是:

instance = place() 
instance.add_directions("The Dark Room")

我希望这能澄清你的疑惑。