首页 > 解决方案 > 将函数参数分配给动态创建的同名类的属性时出现 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'>

标签: pythonpython-3.xpython-3.8

解决方案


推荐阅读