Python 2 动态多重继承

标签 python python-2.7

在 python 3 中,我可以使用列表扩展来动态继承多个父类(super class):

class Super1(object):
    x = 1

class Super2(object):
    y = 1

classes = [Super1, Super2]

class B(*classes):
    pass

这让我可以在运行时决定将哪些混合类添加到父类(super class)列表中。

不幸的是,父类(super class)列表的*扩展是python2中的语法错误。是否有一种普遍接受的方式在运行时选择父类(super class)列表

最佳答案

@blhsing 提供的答案是正确的,但我实际上想要的是 2/3 兼容的东西。我接受了直接使用 type 的提示,并做了更像这样的事情:

class Super1(object):
    x = 1

class Super2(object):
    y = 1

classes = [Super1, Super2]

B = type('B', tuple(classes), {})

这在 2/3 中同样有效

关于Python 2 动态多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55752898/

相关文章:

python - 在 Python 3 中编写 csv

python - 是否有任何资源可以让 Python 2.7 开发人员跟上 Python 3.3 的速度?

python-2.7 - Python - 如何在一行上显示更新值而不是向下滚动屏幕

python - MinGW 对 `_imp__PyExc_TypeError' 的 undefined reference

python - @staticmethod 给出语法错误 : invalid syntax

Python/Pandas - 给定特定日期,查找列表中的前一个日期

python - 类型错误 : unsupported operand type(s) for -: 'str' and 'int' (Python)

python - 使用 Python 读取 csv 文件第 i 列的最佳方法是什么?

python - 使用 python xlrd 从 Excel 单元格获取公式

python - multiprocessing.Value 无法正确存储 float