python - 强制使用专门的子类

标签 python oop polymorphism

当使用某些参数调用父类(super class)时,我试图强制使用更专业的类。具体来说,我有一个 Monomial 类(其 __init__ 采用 coefficient 和 power)和一个 常量类。我希望每当使用 power=0 调用 Monomial 时,都会返回一个 Constant 实例。

这些类的目的是构建用于生成“随机”数学函数的框架。

我最初拥有的:

class Monomial(Function):
    def __init__(self, coef: int, power: int, inner=Identity()):
        super().__init__(inner)
        self.pow = power
        self.coef = coef


class Constant(Monomial):
    def __init__(self, c: int):
        super().__init__(c, 0)

我尝试添加以下 __new__ 方法:

class Monomial(Function):
    def __new__(cls, coef: int, power: int, inner=Identity()):
        if power == 0:
            return Constant(coef)
        instance = object.__new__(Monomial)
        instance.__init__(coef, power, inner)
        return instance

问题是,现在无论何时创建新的Constant,都会调用Monomial__new__ 方法(签名不匹配) .

执行此操作的最佳方法是什么?

最佳答案

如何使用工厂方法方法?当应该动态定义确切的实例类型时,这是一个不错的选择。看起来像:

class Monomial(Function):
    @staticmethod
    def create(coef: int, power: int, inner=Identity()):
        if power == 0:
            return Constant(coef)
        else:
            return Monomial(coef, power)

x = Monomial.create(...)

关于python - 强制使用专门的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53915703/

相关文章:

python - 安装用 C++ : g++ unrecognized command line option --output-lib 编写的 Python 包 (leven) 时出错

Python - Folium map 不显示标记

python - python中平流方程四阶龙格-库塔编程

objective-c - 如何在 Objective-C 中声明类级别的属性?

haskell - 将类型变量约束为具体类型

python - 将字符串值从 pickled 转换为字典

c++ - 来自另一个类的对象的类 vector

python - 从类中的另一个静态方法函数调用函数

java - 访问修饰符继承: on abstract methods

c++ - 子类中的成员对父类成员的引用?