我想知道为什么在调用函数时没有在python3中定义NameError:名称'file‘是没有定义的?
def func(file):
for file in os.listdir(cwd):
if file.endswith('.html'):
f = open(file, "r+")
....
f = open(file, "w")
f.write(text)
在下面的代码中,我定义了两个函数。main和cube.我希望main是我的程序的开始,所以我在main中调用了cube
>>> def main():
number = int(input('Enter a number: '))
cubed_number = cube(number)
print("The number cubed is: ", cubed_number)
>>> def cube(number):
return number * number * number
>
我认为Python语言中的class语句创建了一个作用域。但是尝试这个简单的代码时,我得到了一个错误:
class A():
foo = 1
def __init__(self):
print foo
a = A()
NameError: global name 'foo' is not defined
为什么不能从初始化器访问foo?访问它的正确方式是什么?
在Python 3.5.0中,这段代码如下:
a = (1,2)
class Foo(object):
b = (3,4)
c = tuple((i,j) for j in b for i in a)
d = tuple((i,j) for i in a for j in b)
产生:
Traceback (most recent call last):
File "genexprtest.py", line 2, in <module>
class Foo(object):
File "genexprtest.py&
当我在python(2.6.5)程序中导入和使用一个函数时,我会得到一个错误:
from Localization import MSGR
title = Localization.MSGR("Logfile from Ctf2Rrl.")
NameError:未定义全局名称“本地化”
你能解释一下为什么吗?
致以敬意,
以下是代码:
#a.py
ALL_FUNC = [bar, foo] #a list containing all the functions defined in this module
def bar():
pass
def foo():
pass
然后,我像这样运行它:$ python a.py NameError: name 'bar‘未定义
错误意味着,在执行bar时没有定义ALL_FUNC = [bar, foo]。但是为什么解释器不能在模块中找到函数bar呢?仅仅因为bar是在ALL_FUNC之后定义的
看看这个,这里有一个python类,
clas
我刚读了这个问题的答案:
它帮助我理解为什么下面的代码会导致NameError: name 'x' is not defined
class A:
x = 1
data = [0, 1, 2, 3]
new_data = [i + x for i in data]
print(new_data)
之所以出现NameError,是因为x没有在用于列表理解的特殊范围中定义。但是我无法理解为什么下面的代码在没有错误的情况下工作。
class A:
x = 1
data = [0, 1, 2, 3]
new_data = [i f
当我试图访问dict理解中的类变量时,例如在NameError: name 'ID' is not defined中,我得到了class A。在没有理解的情况下引用时,它可以正常工作(参见class B)。所以我的问题是,为什么它在A类中抛出NameError,而在B类中没有?
class A:
ID = "This is class A."
test = {str(i): ID for i in range(5)}
class B:
ID = "This is class B."
test = f"
我有一个很简单的例子:
#!/usr/bin/env python
#a() # 1: NameError: name 'a' is not defined
#b() # 1: NameError: name 'b' is not defined
#c() # 1: NameError: name 'c' is not defined
def a():
c() # note the forward use here...
#a() #2: NameError: global name 'c' is not
为什么会发生这种NameError?
(插入提示以提高可读性之前的空行。)
$ python3
Python 3.4.10 (default, Oct 4 2019, 19:39:58)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb
>>> def blah():
..
Python (3和2)不允许在其体内引用类(方法除外):
class A:
static_attribute = A()
这将在第二行引发一个NameError,因为'A' is not defined,而
class A:
def method(self):
return A('argument')
效果很好。在其他语言中,例如Java,前者没有问题,在许多情况下都是有利的,比如实现单例。
为什么在Python中这是不可能的?这个决定的原因是什么?
编辑:我编辑了,所以它只要求“绕过”这个限制,而这个问题询问它的动机/技术细节
发行 python 3.8.6
def __foo():
pass
class MyClass:
@staticmethod
def bar():
__foo()
MyClass.bar()
在以下方面的成果:
NameError: name '_MyClass__foo' is not defined
观测
如果我用__foo()代替foo(),它就能正常运行。
我意识到python正在MyClass中寻找MyClass。在C++中,我可以使用::__foo()在模块级别显式调用函数。巨蟒中有类似的吗?
问题
我正在尝试理解Python中嵌套类的作用域。下面是我的示例代码:
class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
类的创建没有完成,我得到了错误:
<type 'exceptions.NameError'>: name 'outer_var' is not defined
尝试inner_var = Outerclass.outer_var不起作用。我得到了:
<type 'exceptions.NameErr
我是一位python新手,试图跟随这个关于寻找季节性顾客的伟大博客:
然而,我被困在最后的一步。守则是:
customerTS = stats.ts(dataForOwner.SENDS.astype(int),
start=base.c(startYear,startMonth),
end=base.c(endYear, endMonth),
frequency=12)
我得到了一个错误:NameError: name 'dataForOwner' is not defined
编辑-我应该补充,这最后一行也在代码块中,但我仍
我目前正致力于创建一个python线性代数模块,用于乐趣和语言实践。我最近尝试将类型注释添加到模块中,如下所示:
class Vector:
# Various irrelevant implementation details
def __add__(self, other: Vector) -> Vector:
# More implementation details....
但是,当我试图导入它时,它会产生一个NameError: Name 'Vector' is not defined。我承认,这个问题已经以的形式得到了回答,
嗨,我正在尝试将我的代码分成2个python文件,以使它更整洁。但后来,我有了一个NameError。
以下是我的简化代码:
report.py
def report():
print result
master.py
from report import *
global result
result = [1,2,3,5,7,9]
report()
当我运行master.py时,我得到了NameError:全局名称‘NameError’是没有定义的。我已经把它定义为全局的,但是不知道为什么它仍然是返回错误。
在我的(简化)脚本中,我有以下内容:
def predict(new_data):
.
.
.
model_list = fetch_needed_models() # ["f1","f2","f3"]
for m in model_list:
with open(f"./{m}.pkl","rb") as file:
exec(f"{m}=pickle.load(file)")
print(dir()) # [...,'f1',
我想按以下方式定义一个类:
class ConfigManager:
@classmethod
def load_config(cls):
# do some complex stuff to load something
return config
__CONFIG = ConfigManager.load_config()
@classmethod
def get_config(cls):
return cls.__CONFIG
然后,当我运行以下代码时,它会报告一个NameError
x = Co
我有一个简单的函数,我将其称为myFunction。它接受两个参数,对它们执行一些计算,然后返回结果。
我还有一个类,MyClass,它有一个构造函数,它有一个头函数,如下所示:
__init__(self, bar, fun=myFunction):
当我试图运行这个类中的任何东西时,我得到以下错误:
MyClass
def __init__(self, bar, fun=myFunction):
NameError: name 'myFunction' is not defined
如果我删除这个类,我就可以在Python Shell中使用myFun,这是怎么回事呢
我现在正在开发一个用Python编写的大型软件系统。
问题是,我不确定如何确保系统中的每个.py文件都是正确的。运行该软件的唯一方法是运行使用所有其他.py文件的main.py文件。
因此,要么一切正常,要么有一件事情不起作用(导致所有事情都不起作用)。
即使导入了正确的文件,我仍然得到一个NameError。我认为这可能与NameError中与该名称相关联的类可能存在错误有关。有什么建议吗?NameError给了我这个:
File "<string>", line 1, in <module>
NameError: name 'RGBox&
我在Windows命令行中遇到这个错误,做了广泛的搜索,但无法获得一个完美的answer.Please找到下面的错误并帮助解决。
python
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>>
提前谢谢你,
在python脚本中,我刚刚将matplotlib升级到1.5.0,现在得到了这个错误:
from matplotlib import pyplot as plt
import matplotlib.ticker as tkr
from matplotlib import rcParams
from mpl_toolkits.basemap import Basemap, maskoceans
cs = m.contourf(x,y,mask_data,numpy.arange(min_range,max_range,step),cmap=PRGn_10.mpl_colormap)
N
我试图用hh:mm来表达时间。我知道冒号告诉python数个小时到几分钟,但这不是我想要的。有人能解释一下纠正我这个错误的方法吗?
def extract_hours(hours:minutes):
"""returns an integer representing the number of hours number, number -> number"""
return (hours)
这是我得到的错误:
NameError: name 'minutes' is not defined
假设在同一个python文件中一个接一个地有两个函数:
def A(n):
B(n-1)
# if I add A(1) here, it gives me an error
def B(n):
if n <= 0:
return
else:
A(n-1)
当解释器正在读取A时,还没有定义B,但是这段代码并没有给出错误。这让我感到困惑,因为我认为Python程序是逐行解释的。为什么在调用任何东西之前,试图在B中调用A时不会立即出现错误?
我的理解是,当解释def时,Python用{"function name": f
在python中,以下功能很好:
def test_foo():
class Foo(object):
pass
class Fam(object):
bar = Foo
test_foo()
但是,以下内容在NameError: name 'Foo' is not defined中失败
def test_foo():
class Foo(object):
pass
class Fam(object):
Foo = Foo
test_foo()
为什么我指定的名称会影响所分配值的
我有一个python脚本,并且收到以下错误:
Traceback (most recent call last):
File "C:\Users\Tim\Desktop\pop-erp\test.py", line 1, in <module>
s = Something()
NameError: name 'Something' is not defined
以下是导致问题的代码:
s = Something()
s.out()
class Something:
def out():
print("
我的印象是,Python中的模块主要是为了提高代码的可读性和代码文档的目的。
在玩过它并阅读了关于模块的内容之后,我设法把自己和它搞混了。
下面的代码可以工作,即使这两个变量没有初始化(通常您会初始化它们,例如a = "test")。
我只是在上面加了一个提示,一切看起来都还好。也就是说,如果我的代码NameError中只有a,我就不会得到一个NameError: name 'a' is not defined。
以这种方式声明变量(带有类型提示)是一种OK实践吗?为什么要这么做?
from typing import Any
test_var: int
a:
我安装了模块python-Levenshtein-0.11.2。我认为设置成功了(当我输入help('modules')时,我在列表中看到了"Levenshtein“模块)。
但是当我尝试“距离”函数时,我得到了一个错误:"NameError: name 'distance' is not defined"。
我不明白为什么距离函数不能工作。