gpt4 book ai didi

python - 类构造函数应该返回子类吗?

转载 作者:太空狗 更新时间:2023-10-30 02:12:56 25 4
gpt4 key购买 nike

类构造函数应该返回子类吗?

这主要是关于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

我的问题是如何设计一个流畅的界面,以便用户获得合适的实例而不必担心它是如何实现的。我考虑过做类似下面的事情,但这对我来说很难看。是否有更规范或 OOP 的方式来做这样的事情?

class MyCounter(object):
"""General Case Counter"""
def __new__(cls, seq):
if hasOnlyHashables(seq):
return object.__new__(OptimizedCounter)
else:
return object.__new__(MyCounter)

最佳答案

使用返回相应类实例的工厂函数。

def makeCounter(seq):
if hasOnlyHashables(seq):
return OptimizedCounter(seq)
else:
return MyCounter(seq)

关于python - 类构造函数应该返回子类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com