【问题标题】:calling a function inside another function in a class?在类的另一个函数中调用一个函数?
【发布时间】:2014-06-13 04:18:51
【问题描述】:

我一直试图在一个类的另一个函数中调用一个函数。这导致了一个错误。我能做些什么来解决这个问题。代码如下:

class Goomba:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def goomleft(self,speed):
        for i in range(speed):
            if mask.get_at((self.x,self.y+10))[0] !=255:
                self.x-=1
    def goommove(self,direction):
        if direction == 'left':
            goomleft(self,3)  #this is where I called it

错误说 NameError:未定义全局名称“goomleft”

【问题讨论】:

    标签: function class python-3.x


    【解决方案1】:

    由于类中函数的作用域不同,因此必须在彼此内部调用函数:

    class Goomba:
        def __init__(self,x,y):
            self.x = x
            self.y = y
        def goommove(self,direction):
            def goomleft(self,speed):
                for i in range(speed):
                    if mask.get_at((self.x,self.y+10))[0] !=255:
                        self.x-=1
            if direction == 'left':
                goomleft(self,3)  #this is where I called it
    

    【讨论】:

    • WAT...这篇文章让我患上了癌症。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多