python – decorator,用于在命名空间中生成新类

我需要它的具体用例是弃用类名.

假设我们在早期版本中有A类,我们想要弃用其名称但保持向后兼容性:

class A(B):
    def __init__(self, *args, **kwargs):
        warnings.warn('deprecation!')
        super(A, self).__init__(*args, **kwargs)

……而B现在有正确的实施.

当我们创建A类时,我们将在此处遇到弃用警告.我们也可以在__init__上使用已弃用的模块用于装饰器.

但是,我想跳过这个过程并编写更少的代码,并希望实现如下:

@deprecated_alias('A')
class B:
    # ... do something

我可以以某种方式将类名注入模块级命名空间,以便我可以像这样使用A吗?

最佳答案 虽然这并不是你所要求的,但它实际上不那么神奇,而且最终的代码行数也相同.它也更明确:

import warnings

def deprecated(DeprecatedByClass):
    class Deprecated(DeprecatedByClass):
        def __new__(cls, *args, **kwargs):
            warnings.warn("deprecation!")
            return super(Deprecated, cls).__new__(cls, *args, **kwargs)

    return Deprecated

然后您可以像这样使用它:

class B:
    pass

A = deprecated(B)
点赞