python - 如何动态设置类名?

标签 python

我有一个函数可以创建从它的参数派生的类:

def factory(BaseClass) :
    class NewClass(BaseClass) : pass
    return NewClass

现在当我用它来创建新类时,这些类都被命名为相同的,并且实例看起来它们具有相同的类型:

NewA = factory(ClassA)
NewB = factory(ClassB)
print type(NewA()) # <class __main__.NewClass>
print type(NewB()) # <class __main__.NewClass>

手动设置 __name__ 属性是否正确?

NewA.__name__ = 'NewA'
print type(NewA()) # <class __main__.NewA>

我在做的时候还需要设置其他的东西吗?

最佳答案

是的,设置 __name__ 是正确的做法;你不需要设置任何其他东西来调整类名。

例如:

def factory(BaseClass) :
    class NewClass(BaseClass): pass
    NewClass.__name__ = "factory_%s" % BaseClass.__name__
    return NewClass

type 是这里使用的错误 东西。它不允许您使用 Python's normal class syntax 定义类,而是让您手动设置每个类属性。它用于手动创建类,例如如果你有一个基类数组并且你想使用它创建一个类(你不能用 Python 的类语法来做)。不要在这里使用它。

关于python - 如何动态设置类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5352781/

相关文章:

python - 如何在python中 append 具有相同前缀的多个数据帧

python - 使用 matplotlib 和 boto 将绘图从内存上传到 s3

python - 在 python 2.7 中并行运行函数以在其他函数末尾使用函数的输出

python - 如何使用 mysqlconnector 在 SQLAlchemy 中设置 FOUND_ROWS 的 client_flags 以返回受影响的行

python - 快速生成带约束的组合的方法?

Python:pickle 错误:__new__() 恰好需要 2 个参数(给定 1 个)

python - 在Python中使用 Storm

python - 我如何在 python 中拆分列表

c++ - cython c++ 对 std::ios_base::failure 的 undefined reference

python - 无法导入 matplotlib