How to create a hidden factory?

I know it was closed before, but I just don't get it ...

I want to create a class that is called with a file name, but, depending on the file name extension, it will be converted to one of several subclasses. He thinks this is a factory pattern, and I did it before using staticmethod, but now I'm trying to do it incompletely to do this with a regular base class instance. Is it possible?

 >>> foo = FileClass('foo.txt')
 >>> type(foo)
 <type 'TextFileClass'>

 >>> foo = FileClass('foo.rtf')
 >>> type(foo)
 <type 'RTFFileClass'>

This is not an actual result, but what I hope to achieve. I try crazy things and should be away from the track. At the moment, I performed the procedure __new__in FileClass, but it may not seem right to her. There seem to be several ways to do this? Which one is right?

+3
source share
3

factory?

class BaseFile(object):
    """Inherit these common methods and properties"""
    def __init__(self, fname):
        self.fname = fname

    def is_pretty(self):
        NotImplemented

class TextFileClass(BaseFile): 
    def is_pretty(self):
        return False

class RTFFileClass(BaseFile):
    def is_pretty(self):
        return True

def createFileClass(fname):
    if fname.endswith('.txt'):
        return TextFileClass(fname)
    elif fname.endswith('.rtf'):
        return RTFFileClass(fname)
    else:
        raise Exception, 'unknown file format'

FileClass = createFileClass

:

>>> foo = FileClass('foo.txt')
>>> type(foo)
<class '__main__.TextFileClass'>

>>> foo = FileClass('foo.rtf')
>>> type(foo)
<class '__main__.RTFFileClass'>
+4

__new__ , FileClass.__new__ TextFileClass, TextFileClass __new__ ?

, , cls __new__, __new__:

def __new__(cls, filename):
    if cls is FileClass:
        return cls._factory(filename)
    return super(FileClass, cls).__new__(cls, filename)

FileClass('foo.txt'), Python __init__ , __new__, FileClass, TextFileClass.__new__('foo.txt') TextFileClass('foo.txt'):

@classmethod
def _factory(cls, filename):
    if filename.endswith('.txt'):
        return TextFileClass.__new__(filename)
    elif filename.endswith('.rtf'):
        return RTFFileClass.__new__(filename)
    ...

, , , . factory factory .

+2

FileClass factory, Handle/Body ( /, FileClass , field proxy. , , .

0
source

All Articles