简体   繁体   English

在python中实例化一个类时返回另一个类

[英]returning another class when instantiating a class in python

I am trying to use logging's memory handler to buffer log messages to my actual logging handler. 我正在尝试使用日志记录的内存处理程序将日志消息缓冲到我的实际日志记录处理程序中。 You use the memory handler by instantiating it with some arguments, like this: 您可以通过使用一些参数实例化来使用内存处理程序,如下所示:

import logging
buffered_handler = logging.handlers.MemoryHandler(capacity=5,target=myActualHandler)

However, I don't want my application to have to instantiate a handler from logging directly, or pass any of the arguments; 但是,我不希望我的应用程序必须直接从日志记录中实例化处理程序或传递任何参数。 I'd like this code to look like this: 我希望这段代码看起来像这样:

import myhandlers
buffered_handler = myhandlers.BufferedRemoteHandler()

The question is: how do I do this? 问题是:我该怎么做? I'd like an attempt to instantiate my BufferedRemoteHandler to actually return logging's MemoryHandler with some specific arguments. 我想尝试实例化BufferedRemoteHandler实际返回带有某些特定参数的日志记录的MemoryHandler。 I thought of just making BufferedRemoteHandler a function which returns the handler I want; 我想到了使BufferedRemoteHandler一个函数返回我想要的处理程序; is that the correct way? 那是正确的方法吗? Is there a way to create a class which, when you instantiate it, actually returns a totally different class? 有没有办法创建一个类,当您实例化它时,它实际上返回一个完全不同的类?

Maybe point 3 of PEP 8 is the answer: 也许PEP 8的第3点是答案:

Simple is better than complex.

I'd go the function way. 我会去功能的方式。 Maybe call it something like get_handler() (or get_buffered_remote_handler() ) though, so you realize it is something other than a real class at first glance. 也许叫它类似get_handler() (或get_buffered_remote_handler() ),所以乍一看您就意识到它不是真正的类。

Yes just make it a function. 是的,只需使其功能即可。 Something like getMemoryHandler(). 诸如getMemoryHandler()之类的东西。 THat's the best way to do it. 这是最好的方法。 Also, if only one instance of MemoryHandler is going to be around you may want to make it a singleton. 另外,如果仅要有一个MemoryHandler实例,则可以将其设为单例。

To answer your exact question, you may, if you like, override __new__() on your subclass to return an instance of a class other than yours. 要回答您的确切问题,您可以根据需要在子类上重写__new__()以返回除您之外的类的实例。

import logging

class BufferedRemoteHandler(object):
   def __new__(cls):
       return logging.handlers.MemoryHandler(capacity=5,target=myActualHandler)

But I'd actually suggest the function. 但是我实际上建议使用该功能。

Well, to answer you directly, yes, there's __new__() . 好吧,直接回答你,是的,有__new__() However, I think what would probably be an easier solution would be to either hard code or allow special handler definitions to be registered to myhandlers. 但是,我认为可能更简单的解决方案是硬编码或允许将特殊的处理程序定义注册到myhandlers。 You'd define a member method for each handler you want in myhandlers that just instantiated the MemoryHandler as you want and returned it. 您将在myhandlers中为所需的每个处理程序定义一个成员方法,该方法仅根据需要实例化MemoryHandler并返回它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM