Bi *_*ico 4 python oop coding-style
类构造函数应该返回一个子类吗?
这主要是关于OOP风格和python风格的问题.我有问题需要实现一般案例解决方案,出于性能原因,我需要为特定输入类型实现优化解决方案.输入类型取决于用户.目前,我已经通过对一般案例解决方案进行子类化来实现这一目标,以制定优化的解决方案.我想出了以下示例来帮助描述我的意思.
from collections import Counter
class MyCounter(object):
"""General Case Counter"""
def __init__(self, seq):
self.seq = seq
def count(self, key):
return sum(key == item for item in self.seq)
class OptimizedCounter(MyCounter):
"""Counter optimized for hashable types"""
def __init__(self, seq):
self.counter = Counter(seq)
def count(self, key):
return self.counter.get(key, 0)
counter = MyCounter(['a', 'a', 'b', [], [0, 1]])
counter.count([0, 1])
# 1
counter = OptimizedCounter(['a', 'a', 'b'])
counter.count('a')
# 2
Run Code Online (Sandbox Code Playgroud)
我的问题是如何设计一个流畅的界面,以便用户获得一个合适的实例,而不必担心它是如何实现的.我考虑过做类似下面的事情,但这对我来说很难看.是否有更规范或OOP的方式来做这样的事情?
class MyCounter(object):
"""General Case Counter"""
def __new__(cls, seq):
if hasOnlyHashables(seq):
return object.__new__(OptimizedCounter)
else:
return object.__new__(MyCounter)
Run Code Online (Sandbox Code Playgroud)
使用返回相应类的实例的工厂函数.
def makeCounter(seq):
if hasOnlyHashables(seq):
return OptimizedCounter(seq)
else:
return MyCounter(seq)
Run Code Online (Sandbox Code Playgroud)