【问题标题】:How to fix "NameError: name method-name is not defined"? [duplicate]如何修复“NameError:名称方法名称未定义”? [复制]
【发布时间】:2017-09-24 15:25:34
【问题描述】:

以下 Python 代码有问题:

class Methods:

    def method1(n):
        #method1 code

    def method2(N):
        #some method2 code
            for number in method1(1):
                #more method2 code

def main():
    m = Methods
    for number in m.method2(4):
            #conditional code goes here

if __name__ == '__main__':
    main()

当我运行这段代码时,我得到了

NameError:名称“method1”未定义。

如何解决此错误?

【问题讨论】:

  • 你需要使用self.method1

标签: python function nameerror


【解决方案1】:

只需添加自我。在它面前:

self.method1(1)

还将您的方法签名更改为:

def method1(self, n):

def method2(self, n):

【讨论】:

  • 非常感谢。它有效!
  • @maestro777,尽情享受吧!
【解决方案2】:

更改您的代码,如下所示:

class Methods:

    def method1(self,n):
        #method1 code

    def method2(self,N):
        #some method2 code
        for number in self.method1(1):
            #more method2 code

def main():
    m = Methods()
    for number in m.method2(4):
        #conditional code goes here

if __name__ == '__main__':
    main()
  1. 为类中的每个方法添加一个 self 参数
  2. 要在类中调用方法,请使用 self.methodName(parameters)
  3. 要创建你的类的实例,你应该用 paranteses 编写类名,例如:m = Methods()

【讨论】:

    猜你喜欢
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 2017-08-30
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多