How to fix "NameError: name method-name is not defined"?
How to fix "NameError: name method-name is not defined"?
我在使用以下 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: name 'method1' is not defined.
如何解决这个错误?
自己加吧。在它前面:
self.method1(1)
同时将您的方法签名更改为:
def method1(self, n):
和
def method2(self, n):
像下面这样更改您的代码:
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()
- 在 class
中的每个方法中添加一个 self 参数
- 要在 class 中调用方法,请使用 self.methodName(参数)
- 要创建您的 class 的实例,您应该写 class 带有括号的名称,例如:m = Methods()
我在使用以下 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: name 'method1' is not defined.
如何解决这个错误?
自己加吧。在它前面:
self.method1(1)
同时将您的方法签名更改为:
def method1(self, n):
和
def method2(self, n):
像下面这样更改您的代码:
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()
- 在 class 中的每个方法中添加一个 self 参数
- 要在 class 中调用方法,请使用 self.methodName(参数)
- 要创建您的 class 的实例,您应该写 class 带有括号的名称,例如:m = Methods()