[英]AttributeError: type object has no attribute (problem with *args?)
注意:这不是AttributeError: type object has no attribute的重复。 我正在尝试编写文本冒险。
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'
我知道我对对象的理解不是很好,但是有人可以帮我在字符串中为 class 变量self.directions
中的每个键分配单独的方向吗? function add_directions
中的*args
有问题吗?
在使用该变量(作为实例)之前,您必须将place()
分配给变量(使其成为实例)。 这就是为什么所有的答案都是:
instance = place()
instance.add_directions("The Dark Room")
我希望这能澄清你的疑虑。
问题出在你的最后两行:
place()
place.add_directions(place, "The Dark Room")
应该:
p = place()
p.add_directions("The Dark Room")
您正在调用place
构造函数,但没有在任何地方分配它。 您不需要为self
传递place
, p.add_directions
中的p
部分自动为self
。
您需要创建 class 地点的实例。 place() - 是 class 地方的实例,地方 - class 本身。 你也不需要为自己传递参数。 它会自动通过。 你的代码应该是
p = place()
p.add_directions("The Dark Room")
PS按照惯例,您应该将 class 的首字母大写
place.add_directions(place, "The Dark Room")
在这一行中,您引用的是 class 地点,而不是地点 class 的实例,
在 python 和其他面向 Object 的编程语言中,您首先需要在访问其成员之前实例化或初始化 class。
place_instance = place()
place_instance.add_directions("The Dark Room")
不必像您所做的那样将 class 作为self
传递, self
需要定义方法,而不是在调用方法时。
要使此代码更具可读性,请考虑使用大写字母作为位置。 它可以写成class Place()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.