装饰者与继承 [英] Decorators versus inheritance

查看:249
本文介绍了装饰者与继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在可能的情况下,如何决定使用装饰器和继承?

How do you decide between using decorators and inheritance when both are possible?

例如,这个问题有两个解决方案。

E.g., this problem has two solutions.

我对Python特别感兴趣。

I'm particularly interested in Python.

推荐答案

其他答案也不错,但我想给出一个简短的利弊清单。

The other answers are quite great, but I wanted to give a succinct list of pros and cons.

mixins的主要优点是可以在运行时使用 isinstance 来检查类型,并且可以使用像MyPy这样的linters来检查它。像所有继承一样,当您具有 is-a 关系时,应使用它。例如, dataclass 应该是一个混合对象,以便公开特定于数据类的自省变量,例如数据类字段的列表。

The main advantage of mixins is that the type can be checked at runtime using isinstance and it can be checked with linters like MyPy. Like all inheritance, it should be used when you have an is-a relationship. For example dataclass should probably have been a mixin in order to expose dataclass-specific introspection variables like the list of dataclass fields.

装饰器如果您没有 is-a 关系,则应首选。例如,一个装饰器从另一个类传播文档,或在一个类中注册一个类。

Decorators should be preferred when you don't have an is-a relationship. For example, a decorator that propagates documentation from another class, or registers a class in some collection.

装饰通常只影响它装饰的类,而不影响从基类继承的类:

Decoration typically only affects the class it decorates, but not classes that inherit from the base class:

@decorator
class A:
    ...  # Can be affected by the decorator.

class B(A):
    ...  # Not affected by the decorator in most cases.

现在Python具有 __ init_subclass __ ,装饰者可以做的一切用mixins完成,它们通常确实会影响子子类:

Now that Python has __init_subclass__, everything that decorators can do can be done with mixins, and they typically do affect child subclasses:

class A(Mixin):
    ... # Is affected by Mixin.__init_subclass__.

class B(A):
    ... # Is affected by Mixin.__init_subclass__.

总而言之,在决定混搭和装饰时应该问的问题是:

In summary, the questions you should ask when deciding between a mixin and decoration are:


  • 是否存在是-模式?

    • 您会打电话给 instancetance 吗?

    • 您是否会在其中使用mixin类型注释?

    • Is there an is-a pattern?
      • Would you ever call isinstance?
      • Would you use the mixin in a type annotation?

      这篇关于装饰者与继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆