假设我有一个包含子类ShortWord
和LongWord
的Word
类。有没有一种方法可以根据给定的输入动态地确定哪个子类被实例化?我的意思是,我可以定义一个单独的函数,比如
def instantiate(text):
if len(text) < 5:
return ShortWord(text)
else:
return LongWord(text)
但这感觉不太优雅(因为没有更好的词(。有什么好办法吗?我在其他语言中发现了一些类似的问题,但没有python特有的问题。
我会在基类中定义一个@staticmethod
来进行确定。
您可能需要在基类中定义__init_subclass__
,以便至少了解存在哪些类,因为在定义基类之前,您并不了解子类。
class Word(object):
_tr = {} # Type registry
@staticmethod
def instantiate(text):
if len(text) < 5:
cls = __class__._tr.get('ShortWord')
else:
cls = __class__._tr.get('LongWord')
return cls(text) if cls is not None else None
def __init_subclass__(cls):
__class__._tr[cls.__name__] = cls
class ShortWord(Word):
pass
class LongWord(Word):
pass
我在看到评论后仔细考虑了一下,这是另一种方法。我不想为一个问题提交两个答案。更新:感谢@chepner的评论,我进一步清理了它。
class Word(object):
@staticmethod
def instantiate(text):
if len(text) < 5:
return ShortWord(text)
else:
return LongWord(text)
class ShortWord(Word):
pass
class LongWord(Word):
pass
用val = Word.instantiate(text)
实例化