問題描述
我寫了以下課程:
class myClass(object):
def __init__(self):
pass
def foo(self, arg1, arg2):
pp = foobar(self, arg1, arg2)
if pp:
return 42
else
return -666
def foobar(self, arg1, arg2):
if arg1 == arg2:
return 42
else:
return None
邏輯是荒謬的 - 忽略它.我試圖這樣做是從另一個實例方法調用一個實例方法 - 我得到一個 NameError
.我最初認為這是由于 foo()
在定義之前調用了 foobar()
- 但是在腳本中切換函數定義的順序沒有任何區別.
The logic is nonsensical - ignore it. What I am trying to so is to call an instance method from another instance method - and I am getting a NameError
. I originally thought that this was due to foo()
calling foobar()
before it had been defined - but switching the order of the function definitions in the script made no difference.
有沒有人知道是什么導致了這個錯誤,以及如何解決它?
Does anyone what's causing this error, and how to fix it?
推薦答案
Python 不會自動將代碼范圍限定為本地類;你需要告訴它.
Python doesn't scope code to the local class automatically; you need to tell it to.
pp = self.foobar(arg1, arg2)
http://docs.python.org/tutorial/classes.html
這篇關于Python:NameError:未定義全局名稱“foobar"的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!