代码之家  ›  专栏  ›  技术社区  ›  darkhorse

如何在运行时使用类型定义具有内部类的类?

  •  0
  • darkhorse  · 技术社区  · 5 年前

    假设我想使用 type 运行时中的方法:

    class Outer(object):
        one = 'one'
        two = 'two'
    
        class Inner:
            three = 'three'
            four = 'four'
    

    Outer = type('Outer', (object,), {'one': 'one', 'two': 'two', ...})
    

    不幸的是,我不知道如何定义内部类。我该怎么做?

    0 回复  |  直到 5 年前
        1
  •  0
  •   darkhorse    5 年前

    Outer = type(
        'Outer', 
        (object,), 
        {
            'one': 'one',
            'two': 'two',
            'Inner': type(
                'Inner',
                (),
                {
                    'three': 'three',
                    'four': 'four'
                }
            )
        }
    )