在python中,当移除的类被用户子类化时,如何理解错误?

2024-10-02 10:28:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为django1.8更新^{},结果发现SQLDateCompiler在1.8版中完全从django中删除了。django_pyodbc正在扩展SQLDateCompiler(我们称之为SQLDateCompilerPrime),它现在已经不存在了。你知道吗

当用户在实例化类之前从SQLDateCompiler继承时,我想发出一个弃用错误/异常。你知道吗

我知道如何使用python的^{}库来引发异常,但是如何在使用类之前引发可理解的异常呢。也就是说,一旦定义了一个子类。你知道吗

我可以做:

class SQLDateCompilerPrime(object):
    def __init__(self, *args, **kwargs):
        warnings.warn(
            'In the 1.8 release of django, `SQLDateCompiler` was removed.  ' +
            'This was the basis of `SQLDateCompilerPrime`, and thus ' +
            '`SQLDateCompilerPrime` is no longer available.',
            DeprecationWarning, stacklevel=2)

但是,这只会在创建子类的实例时失败。我想在子类定义为时失败,并立即发出警告。完全删除该定义肯定会导致失败,但我不希望用户必须查看其他django_pyodbc才能发现它不再是定义的,只是从它们下面消失了。你知道吗


Tags: ofthedjango实例用户定义object错误
1条回答
网友
1楼 · 发布于 2024-10-02 10:28:00

您可以为此使用元类:

class DeprecatedMeta(type):
    def __new__(cls, name, bases, attrs):
        # if the metaclass is defined on the current class, it's not
        # a subclass so we don't want to warn.
        if attrs.get('__metaclass__') is not cls:
            print 'deprecated:', name
        return super(DeprecatedMeta, cls).__new__(cls, name, bases, attrs)


class Foo(object):
    __metaclass__ = DeprecatedMeta


class Bar(Foo):
    pass


class FooBar(Bar):
    pass

此示例产生以下输出:

deprecated: Bar
deprecated: FooBar

相关问题 更多 >

    热门问题