如何摆脱make\u xxx()方法?

2024-10-06 07:42:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有2节课(例如)

class FilePath(Path):
    pass

class DirectoryPath(Path):
    pass

我选择哪个被makepath()方法实例化,simplified

def makepath(string):
    if os.path.isfile(string):
        return FilePath(string)
    return DirectoryPath(string)

我已经多年不喜欢make\u xxx()方法了。它让我想起了太多的Java工厂,所以我想知道是否还有一个更像python的成语?你知道吗


Tags: path实例方法stringreturnifosdef
2条回答

在这种情况下,“path”听起来不错。 由于makepath方法返回或目录或文件路径,所以just path看起来更一般、更简短!你知道吗

def path(string):
    if os.path.isfile(string):
        return FilePath(string)
    return DirectoryPath(string)

还有其他解决方案(比如重写Path.__new__),但是

  1. 它仍然是一个工厂
  2. 很有可能它会因为没有好的理由而变得更加复杂,这本身就足以使它变得不和谐。你知道吗

为了便于说明,下面是一个Q&D示例,使用abc查找适当的具体子类,而不在基类中对子类进行harcoding:

import os
import abc

class Path(object):
    __metaclass__ = abc.ABCMeta

    def __new__(cls, path):       
        imp = cls._get_subclass_for(path)
        instance = super(Path, cls).__new__(imp)
        return instance

    def __init__(self, path):
        self.path = path

    @classmethod
    def _get_subclass_for(cls, path):
        #import pdb; pdb.set_trace()
        for subclass in cls.__subclasses__():
            if subclass.match(path):
                return subclass
        raise LookupError("No matching subclass for path '%s'" % path)

    @staticmethod
    @abc.abstractmethod
    def match(path):
        return False


@Path.register
class FilePath(Path):
    @staticmethod
    def match(path):
        return os.path.isfile(path)


@Path.register
class DirectoryPath(Path):
    @staticmethod
    def match(path):
        return os.path.isdir(path)

相关问题 更多 >