【问题标题】:function name is undefined in python class [duplicate]python类中未定义函数名[重复]
【发布时间】:2015-05-02 12:34:11
【问题描述】:

我对 python 比较陌生,我在命名空间方面遇到了一些问题。

class a:
    def abc(self):
        print "haha" 
    def test(self):
        abc()

b = a()
b.test() #throws an error of abc is not defined. cannot explain why is this so

【问题讨论】:

  • 它正在工作,class a 的函数abc() 被其实例调用。
  • 我认为您对b.test() 的调用而不是b.abc() 应该会引发错误。那是因为您应该使用类实例的引用调用abc()。只需在test()class a 函数中将abc() 替换为self.abc()

标签: python nameerror


【解决方案1】:

为了从同一个类中调用方法,你需要self关键字。

class a:
    def abc(self):
        print "haha" 
    def test(self):
        self.abc() // will look for abc method in 'a' class

如果没有 self 关键字,python 会在全局范围内寻找 abc 方法,这就是您收到此错误的原因。

【讨论】:

    【解决方案2】:

    由于test() 不知道abc 是谁,所以当你调用b.test()(调用b.abc() 很好)时,你看到的消息NameError: global name 'abc' is not defined 应该会发生,请将其更改为:

    class a:
        def abc(self):
            print "haha" 
        def test(self):
            self.abc()  
            # abc()
    
    b = a()
    b.abc() #  'haha' is printed
    b.test() # 'haha' is printed
    

    【讨论】:

      猜你喜欢
      • 2019-01-16
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2014-05-27
      相关资源
      最近更新 更多