使用装饰器和通过继承扩展子类之间有什么区别? [英] What is the difference between using decorators and extending a sub class by inheritance?

查看:103
本文介绍了使用装饰器和通过继承扩展子类之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用python将大脑包裹在Decorators上,但无法理解为什么我们不能通过使用子类来实现相同的目的?

I was trying to wrap my brain around Decorators in python but can't understand why we cannot achieve the same thing by using sub classes?

推荐答案

您可以使用子类来实现相同的目的,而实际上甚至不需要子类-您还可以通过将方法包装到另一个方法中并重新分配它来实现相同的目的。关于是否应将装饰器语法添加到该语言中,引起了很多讨论,因为它不允许您进行任何新操作,并且要求程序员学习更多新内容。

You can achieve the same thing using subclasses, and in fact you don't even need subclasses - you can also achieve the same thing simply by wrapping a method in another method and reassigning it. There was a lot of discussion about whether or not the decorator syntax should be added to the language as it doesn't allow you to do anything new and requires programmers to learn one more new thing.

语法问题是使许多人已经在使用的模式正式化,并使其成为具有名称和使用指南的标准语法。 $ b $ $ b $不必使用装饰器-您可以通过其他方式达到相同的效果-但使用带有简明易懂的语法的官方支持的标准方法可以使生活更轻松。

What the syntax dooes is formalize a pattern that many people were already using, and make it to a standard syntax that has a name and guidelines of how to use. It is not necessary for you to use decorators - you can achieve the same effect in other ways - but using the officially supported standard approach with a concise, easy-to-read syntax makes life a bit easier.

这篇关于使用装饰器和通过继承扩展子类之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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