简体   繁体   中英

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. I thought of just making BufferedRemoteHandler a function which returns the handler I want; 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:

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.

Yes just make it a function. Something like 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.

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.

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__() . 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. You'd define a member method for each handler you want in myhandlers that just instantiated the MemoryHandler as you want and returned it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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