使用元类的 __call__ 方法而不是 __new__? [英] Using the __call__ method of a metaclass instead of __new__?

查看:38
本文介绍了使用元类的 __call__ 方法而不是 __new__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在讨论元类时,文档声明:

您当然也可以覆盖其他类方法(或添加新的方法);例如定义一个自定义的 __call__() 方法元类允许在调用类时自定义行为,例如不是总是创建一个新实例.

You can of course also override other class methods (or add new methods); for example defining a custom __call__() method in the metaclass allows custom behavior when the class is called, e.g. not always creating a new instance.

我的问题是:假设我想在调用类时具有自定义行为,例如缓存而不是创建新对象.我可以通过覆盖类的 __new__ 方法来做到这一点.我什么时候想用 __call__ 来定义元类?这种方法有什么用 __new__ 无法实现的?

My questions is: suppose I want to have custom behavior when the class is called, for example caching instead of creating fresh objects. I can do this by overriding the __new__ method of the class. When would I want to define a metaclass with __call__ instead? What does this approach give that isn't achievable with __new__?

推荐答案

您的问题的直接答案是:当您想要做更多而不仅仅是自定义实例创建时,或者当您想要分离类的作用是如何创建的.

The direct answer to your question is: when you want to do more than just customize instance creation, or when you want to separate what the class does from how it's created.

请参阅我对在 Python 中创建单例的回答以及相关讨论.

See my answer to Creating a singleton in Python and the associated discussion.

有几个优点.

  1. 它允许您将类做什么与其创建方式的细节分开.元类和类各自负责一件事.

  1. It allows you to separate what the class does from the details of how it's created. The metaclass and class are each responsible for one thing.

您可以在元类中编写一次代码,并使用它来自定义多个类的调用行为,而无需担心多重继承.

You can write the code once in a metaclass, and use it for customizing several classes' call behavior without worrying about multiple inheritance.

子类可以覆盖它们的 __new__ 方法中的行为,但是元类上的 __call__ 甚至不必调用 __new__ 在全部.

Subclasses can override behavior in their __new__ method, but __call__ on a metaclass doesn't have to even call __new__ at all.

如果有设置工作,可以在元类的__new__方法中进行,而且只发生一次,而不是每次调用类时.

If there is setup work, you can do it in the __new__ method of the metaclass, and it only happens once, instead of every time the class is called.

当然,如果您不担心单一职责原则,那么自定义 __new__ 肯定会在很多情况下也能正常工作.

There are certainly lots of cases where customizing __new__ works just as well if you're not worried about the single responsibility principle.

但是还有其他用例必须更早地发生,在创建类时,而不是在创建实例时.当这些发挥作用时,元类是必要的.请参阅元类的(具体)用例是什么在 Python 中?有很多很棒的例子.

But there are other use cases that have to happen earlier, when the class is created, rather than when the instance is created. It's when these come in to play that a metaclass is necessary. See What are your (concrete) use-cases for metaclasses in Python? for lots of great examples.

这篇关于使用元类的 __call__ 方法而不是 __new__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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