避免使用元类继承生成的类属性

时间:2017-05-09 07:22:10

标签: python inheritance metaclass

我正在考虑自动将子类添加到父级,以便使用元类“链接”。但是,从父类继承这些属性会让事情变得混乱。有一种很好的方法可以避免这种情况吗?

class MetaError(type):
    def __init__(cls, name, bases, attrs):
        for base in bases:
            setattr(base, name, cls)
        super(MetaError, cls).__init__(name, bases, attrs)

class BaseError(Exception, object):

    def __init__(self, message):
        super(BaseError, self).__init__(message)

class HttpError(BaseError):
    __metaclass__ = MetaError

class HttpBadRequest(HttpError):
    pass

class HttpNotFound(HttpError):
    pass

class FileNotFound(HttpNotFound):
    pass

class InvalidJson(HttpBadRequest):
    pass

http = HttpError

#  now I can do
raise http.HttpNotFound('Not found')
raise http.HttpNotFound.FileNotFound('File not found')
raise http.HttpBadRequest.InvalidJson('Invalid json')

#  unfortunately this also works
raise http.HttpBadRequest.HttpBadRequest('Bad request')
raise http.HttpBadRequest.HttpNotFound('Not found')

2 个答案:

答案 0 :(得分:1)

嗯,事实证明这比起初看起来更棘手 - 因为基本上你想拥有类继承关系,但是不要在类继承上使用普通的属性查找路径 - 否则,HTTPError(作为BaseError的子类)将始终具有BaseError本身中存在的所有属性 - 因此, 链BaseError.HTTPError.HTTPError.HTTPError.HTTPError...始终有效。

幸运的是,Python 提供一种机制来将类注册为其他类的子类,而没有" physical"继承 - 也就是说,它被报告为子类,但在其基础或__mro__中没有父类 - 因此,派生类(采用?)上的属性查找不会搜索&#34中的属性;培育"父节点。

此机制通过" abstract base classes"提供。通过ABCMeta Metaclass和"注册"方法

现在,由于你也可能想宣布这一事实 你的类层次结构使用普通的继承语法 - 也就是说, 能够写class HTTPError(BaseError):来表示新的 class派生自BaseError - 你得到实际的"物理"继承。

因此,我们可以继承ABCMeta类(而不是type)并编写 __new__方法,以便排除物理继承 - 我们也使用setattr包含您对代码的遏制,并且我们直接在元类上触发对parentclass.register的所需调用。

(注意,由于我们现在正在改变基类,我们需要摆弄 在元类的__new__方法中,而不是__init__

from abc import ABCMeta

class MetaError(ABCMeta):
    def __new__(metacls, name, bases, attrs):

        new_bases = []
        base_iter = list(reversed(bases))
        seen = []
        register_this = None
        while base_iter:
            base = base_iter.pop(0)
            if base in seen:
                continue
            seen.append(base)
            if isinstance(base, MetaError):
                register_this = base
                base_iter = list(reversed(base.__mro__))  + base_iter
            else:
                new_bases.insert(0, base)
        cls = super(MetaError, metacls).__new__(metacls, name, tuple(new_bases), attrs)
        if register_this:
            setattr(register_this, name, cls)
            register_this.register(cls)
        return cls

快速测试:

class BaseError(Exception):
    __metaclass__ = MetaError
class HTTPError(BaseError):
    pass
class HTTPBadRequest(HTTPError):
    pass

在交互模式下,检查它是否按预期工作:

In [38]: BaseError.HTTPError
Out[38]: __main__.HTTPError

In [39]: BaseError.HTTPError.HTTPError
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-39-5d5d03751646> in <module>()
----> 1 BaseError.HTTPError.HTTPError

AttributeError: type object 'HTTPError' has no attribute 'HTTPError'

In [40]: HTTPError.__mro__
Out[40]: (__main__.HTTPError, Exception, BaseException, object)

In [41]: issubclass(HTTPError, BaseError)
Out[41]: True

In [42]: issubclass(HTTPBadRequest, BaseError)
Out[42]: True

In [43]: BaseError.HTTPError.HTTPBadRequest
Out[43]: __main__.HTTPBadRequest

In [44]: BaseError.HTTPBadRequest
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-44-b40d65ca66c6> in <module>()
----> 1 BaseError.HTTPBadRequest

AttributeError: type object 'BaseError' has no attribute 'HTTPBadRequest'

然后,最重要的是,测试Exception层次结构是否真的以这种方式工作:

In [45]: try:
   ....:     raise HTTPError
   ....: except BaseError:
   ....:     print("it works")
   ....: except HTTPError:
   ....:     print("not so much")
   ....: 
it works

一些注意事项:无需明确地继承Exceptionobject - Exception本身已经从object继承。而且,最重要的是:无论你正在做什么项目,都可以做任何事情将它移动到Python 3.x而不是Python 2.Python 2可以计算日期,Python 3中有很多很多新功能你是不包括使用。 (这个答案中的代码与Python 2/3兼容,但当然是__metaclass__用法声明)。

答案 1 :(得分:0)

一个相当天真的全球映射解决方案似乎也在起作用:

m = {}
class MetaError(type):

    def __init__(cls, name, bases, attrs):
        for base in bases:
            m[(base, name)] = cls 
        super(MetaError, cls).__init__(name, bases, attrs)

    def __getattribute__(self, value):
        if (self, value) in m:
            return m[self, value]
        return type.__getattribute__(self, value)

class BaseError(Exception):
    __metaclass__ = MetaError

class HttpError(BaseError):
    pass

class HttpBadRequest(HttpError):
    pass

class HttpNotFound(HttpError):
    pass

class FileNotFound(HttpNotFound):
    pass

class InvalidJson(HttpBadRequest):
    pass