如何使go功能正常工作?

2024-04-26 13:44:07 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试在这里进行文本冒险。我正在设置动作模块,并测试动作,但代码一直告诉我我的功能没有定义,即使我在代码中定义了它们(在播放器模块中无法识别),我被卡住了,有什么想法吗

错误:

go_north(self)
NameError: name 'go_north' is not defined

代码:

def go(self, dx, dy):
        self.location_x += dx
        self.location_y += dy
        print(world.tile_exists(self.location_x, self.location_y).intro_text())

        def go_north(self):
            self.go(dx=0, dy=-1)

        def go_south(self):
            self.go(dx=0, dy=1)
 
        def go_east(self):
            self.go(dx=1, dy=0)
 
        def go_west(self):
            self.go(dx=-1, dy=0)

game = "play"
while game == "play":
    x = input()
    y = " is not a valid command"
    string = x + y
    
    if x == "go north":
        go_north(self)

    if x == "go south":
        go_south(self)

    if x == "go east":
        go_east(self)

    if x == "go west":
        go_west(self)

    else:
        print(string)

Tags: 模块代码selfgoif定义deflocation
3条回答

尝试self.go_north()而不是go_north(self)

Kunal Katiyar是对的,但也不要忘记在调用任何函数之前列出所有函数(定义它们),我遇到了一个错误,挣扎了30分钟,因为我在代码前面调用的函数是后来定义的

python初学者的常见错误-类中定义的函数不是全局函数。 首先要初始化“go”实例:

var_name = go()

然后通过其变量名调用函数:

var_name.go_north()

此外,调用函数时不需要将“self”传递到函数中

此外,在类内部调用类函数时,请使用self调用它:

self.whatever()

为了能够将变量传递到类函数中,只需按常规操作,但请记住(在调用时)排除“self”

相关问题 更多 >