【问题标题】:How can I create classes with different class attributes within a function? [duplicate]如何在函数中创建具有不同类属性的类? [复制]
【发布时间】:2020-08-11 02:15:57
【问题描述】:

我想要一个允许生成具有自定义类属性的类的函数。像这样:

def test_factory(a):
    class Test:
        a = a
    return Test

但是,当我尝试调用 test_factory 时,我收到错误消息:

test_factory(1)
> NameError: name 'a' is not defined

预期的行为是:

t1 = test_factory(1)
t2 = test_factory(2)
print(t1.a, t2.a)
> 1, 2

如何通过调用函数来创建类属性不同的类?

【问题讨论】:

  • 好像你来自JS。更 Pythonic 的方式是使用字典
  • 我找到了这个link。可能值得一读
  • 请注意,如果Test 是一个函数而不是一个类,您会收到类似的错误。 Python 中的 Name resolution rules 导致每个赋值都暗示该变量是该块的本地变量。
  • @MaxxikCZ 谢谢 - 这个链接确实值得一读。

标签: python python-3.x


【解决方案1】:

您必须重命名函数参数,以免与类属性的名称冲突:

def test_factory(b):
    class Test:
        a = b
    return Test

>>> t1 = test_factory(1)
>>> t2 = test_factory(2)
>>> print(t1.a, t2.a)
1 2

【讨论】:

    【解决方案2】:

    在解析class 语句时,对a 的赋值将其定义为临时类命名空间的一部分,类似于函数定义中对局部变量的赋值。因此,名称 a 会隐藏封闭函数范围内的参数名称。

    您可以更改参数名称(如图by schwobaseggl

    def test_factory(a_value):
        class Test:
            a = a_value
        return Test
    

    或者在定义之后设置属性:

    def test_factory(a):
        class Test:
            pass
        Test.a = a
        return Test
    

    或直接致电type

    def test_factory(a):
        return type('Test', (), {'a': a})
    

    【讨论】:

      猜你喜欢
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2011-03-13
      • 2023-02-14
      相关资源
      最近更新 更多