Python元类与类装饰器 [英] Python metaclasses vs class decorators

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

问题描述

Python元类和类装饰器之间的主要区别是什么?有什么我可以做的但不能解决的吗?

解决方案

装饰器要简单得多,也要受限制得多,因此,只要可以用元类或类装饰器来达到预期的效果,装饰器就应该是首选. /p>

您可以使用类装饰器做任何事情,当然也可以使用自定义元类(只需应用装饰器函数"的功能,即在过程中使用一个类对象并对其进行修改的功能)元类的__new____init__组成类对象!-).

您可以在自定义元类中执行很多操作,但不能在装饰器中执行许多操作(当然,除非装饰器内部生成并应用自定义元类-但这是作弊行为;-)...甚至在Python中3,有些事情您只能使用自定义元类来完成,而不是事后……但这是您问题的相当高级的子领域,因此,让我给出更简单的示例).

例如,假设您要创建一个类对象X,以使print X(或者在Python 3 print(X)中,当然;-)显示peekaboo!.如果没有自定义元类,就不可能做到这一点,因为元类对__str__的覆盖是此处的关键角色,即,您需要在类X的自定义元类中使用def __str__(cls): return "peekaboo!".

这同样适用于所有魔术方法,即适用于类对象本身的各种操作(与之相反,适用于其 instances 的操作则使用如类-对类对象本身的操作使用了元类中定义的魔术方法.

What are the main differences between Python metaclasses and class decorators? Is there something I can do with one but not with the other?

解决方案

Decorators are much, much simpler and more limited -- and therefore should be preferred whenever the desired effect can be achieved with either a metaclass or a class decorator.

Anything you can do with a class decorator, you can of course do with a custom metaclass (just apply the functionality of the "decorator function", i.e., the one that takes a class object and modifies it, in the course of the metaclass's __new__ or __init__ that make the class object!-).

There are many things you can do in a custom metaclass but not in a decorator (unless the decorator internally generates and applies a custom metaclass, of course -- but that's cheating;-)... and even then, in Python 3, there are things you can only do with a custom metaclass, not after the fact... but that's a pretty advanced sub-niche of your question, so let me give simpler examples).

For example, suppose you want to make a class object X such that print X (or in Python 3 print(X) of course;-) displays peekaboo!. You cannot possibly do that without a custom metaclass, because the metaclass's override of __str__ is the crucial actor here, i.e., you need a def __str__(cls): return "peekaboo!" in the custom metaclass of class X.

The same applies to all magic methods, i.e., to all kinds of operations as applied to the class object itself (as opposed to, ones applied to its instances, which use magic methods as defined in the class -- operations on the class object itself use magic methods as defined in the metaclass).

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

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