Python中gate类实例化时无法接收参数的问题求助
解决Python类实例化时“不接受参数”的错误
核心问题出在构造函数的拼写错误:你把Python的构造函数__init__写成了__innit__(多了一个字母n)。
Python中,类的构造函数必须严格写成__init__(前后各两个下划线,中间是init)。如果拼写错误,Python会自动使用默认的无参构造函数,这就导致你调用gate("north", deep_forest_area)时,程序认为gate类不接受任何参数,直接报错。
你需要把level和gate类里的__innit__全部改成__init__,修正后的代码如下:
# EXCRIPT OF TEXT BASED ADVENTURE OOP PYTHON PROGRAM # defines level class class level(): def __init__(self): self.name = "" # level setup function def setup(self, name, directions, description): self.name = name self.directions = directions self.description = description def enter(self): print(self.description) if len(self.directions) >= 1: print("there is a gate to ", end=" ") for d in self.directions: d.print_gate() # defines gate class class gate: def __init__(self, direction, gate_to): self.gate_to = gate_to self.direction = direction def is_gate(self, text): return self.direction in text def print_gate(self): print("the %s," % self.direction, end= " ") # initialises levels start_area = level() deep_forest_area = level() # defines gates and levels gate1 = gate("north", deep_forest_area) start_area.setup("forest", [gate1], "You are in a dusk lit forest surrounded by trees. The only direction is deeper into the forest") gate1 = gate("south", start_area) deep_forest_area.setup("deep forest", [gate1], "You are in a seemingly endless tunnel of dark oak trees")
另外补充个小建议:按照Python的PEP8编码规范,类名应该使用大驼峰命名法,比如把level改成Level,gate改成Gate,这样代码可读性更强,也符合行业惯例。
内容的提问来源于stack exchange,提问作者Bow the bro
相关产品推荐
相关产品推荐

