Python: NameError: global name #39;foobar#39; is not defined(Python:NameError:未定义全局名称“foobar)
问题描述
我写了以下课程:
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"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python:NameError:未定义全局名称“foobar"
				
        
 
            
        基础教程推荐
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 - PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - 包装空间模型 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				