类构造函数应该返回一个子类吗? [英] Should a class constructor return a subclass?

查看:126
本文介绍了类构造函数应该返回一个子类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类构造函数是否应该返回一个子类?

Should a class constructor return a subclass?

这主要是关于OOP风格和Python风格的问题。我有问题,我需要实现一般case解决方案,并且,出于性能原因,我需要为特定的输入类型实现一个优化的解决方案。输入类型取决于用户。目前,我已经实现了这个子类的一般case解决方案,以使优化的解决方案。我想出了以下示例来帮助描述我的意思。

This is mostly a question about OOP style and python style. I have problem where I need to implement a general case solution and, for performance reasons, I need to implement an optimized solution for a specific input type. The input type depends on the user. Currently I've implemented this by sub-classing the general case solution to make the optimized solution. I've come up with the following example to help describe what I mean.

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方式来做这样的事情?

My question is how do I design a smooth interface so that the user gets an appropriate instance without having to worry about how it's implemented. I've considered doing something like the following, but that feels ugly to me. Is there a more canonical or OOP way to do something like this?

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)

这篇关于类构造函数应该返回一个子类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆