Improper use of __new__ to generate classes?

后端 未结 3 1237
我寻月下人不归
我寻月下人不归 2020-11-29 04:05

I\'m creating some classes for dealing with filenames in various types of file shares (nfs, afp, s3, local disk) etc. I get as user input a string that identifies the data

3条回答
  •  孤独总比滥情好
    2020-11-29 04:48

    In my opinion, using __new__ in such a way is really confusing for other people who might read your code. Also it requires somewhat hackish code to distinguish guessing file system from user input and creating Nfs and LocalDrive with their corresponding classes.

    Why not make a separate function with this behaviour? It can even be a static method of FileSystem class:

    class FileSystem(object):
        # other code ...
    
        @staticmethod
        def from_path(path):
            if path.upper().startswith('NFS://'): 
                return Nfs(path)
            else: 
                return LocalDrive(path)
    

    And you call it like this:

    data1 = FileSystem.from_path('nfs://192.168.1.18')
    data2 = FileSystem.from_path('/var/log')
    

提交回复
热议问题