1

我是 python 新手,一直在练习类和方法。当我运行包含以下代码的脚本时,我收到错误“NameError:未定义全局名称“nameCheck”。” 我该如何解决?提前致谢。

class game(object):
    def play(): 
         name = input("What's your name, my friend? ")
         check = nameCheck(name)

         if check == 1:
             print ("Hello %r " %(name))
         else:
             print ("Sorry, I can't print your name because you don't have one!")


    def nameCheck(name):
         if name == "":
             print("I can't believe you have no name!")
             return 0

         else:
             print("%s is a nice name!" %name)
             return 1
game.play()

Python“NameError:未定义全局名称”nameCheck“。”</p>

4

2 回答 2

3

由于这些方法在一个类中,因此您需要提供 self 属性:

做这个:

class game(object):
    def play(self): 
         name = input("What's your name, my friend? ")
         check = self.nameCheck(name)

         if check == 1:
             print ("Hello %r " %(name))
         else:
             print ("Sorry, I can't print your name because you don't have one!")


    def nameCheck(self, name):
         if name == "":
             print("I can't believe you have no name!")
             return 0

         else:
             print("%s is a nice name!" %name)
             return 1
game = Game()
game.play()

theself是实例的占位符,因此您必须通过执行此操作来创建对象的实例,game = game()然后您可以调用该实例的任何方法

现在你可以从类中的任何地方调用该方法,如果你给变量 self 属性,它们也可以在类中的任何地方访问

更多关于自我

于 2013-10-13T21:08:02.533 回答
2

在类中,Python 函数称为方法,使用如下:

class game(object):

    def play(self):
        self.nameCheck(name)

    def nameCheck(self):
        pass

包含类的self对象。

于 2013-10-13T21:07:09.103 回答