python - 将函数参数分配给动态创建的同名类的属性时出现 NameError
问题描述
我在尝试在函数中创建动态类时遇到了一些奇怪的行为。当我尝试将函数参数分配给同名的类属性时,NameError
会引发 a。我可以通过更改其中一个名称来解决这个问题,但我很困惑为什么会发生这种情况。(我使用的是 Python 3.8.2)
def f(i):
class G:
i = i
return G
def x(a):
class Y:
b = a
return Y
外壳中的结果:
>>> f(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
File "<stdin>", line 3, in G
NameError: name 'i' is not defined
>>> x(1)
<class '__main__.x.<locals>.Y'>
解决方案
推荐阅读
- audio - 检测wav文件中是否有语音
- c - 为什么我们只包含头文件而不包含源文件?
- html - html div没有占据浏览器的全高
- nestjs - 如何在 NestJS 中使用警卫保护代理
- visual-studio-code - 如何让 Visual Studio 代码消耗更少的内存?
- excel - 查找一行中某个值的最后一个实例
- c# - 未经同意提示/许可的 Docusign 身份验证对电子邮件传递应用程序的每个用户进行
- docker - Dokcer Swarm - 网络沙箱加入失败:“10.0.0.0/24”的子网沙箱加入失败:创建 vxlan 接口时出错:文件存在
- javascript - Date.getMonth() 是使用 Date.setMonth() 后的错误
- python - 无法加载 spaCy 模型“en_core_web_sm”