首页 > 解决方案 > 未实现方法

问题描述

我想在 iFuzzBool 类中取消实现方法neg () 和index (),但是当我创建一个实例时,'-' 完美地打印了负值。我究竟做错了什么?

class iFuzzBool(float):

    def __new__(cls, value=0.0):
         return super().__new__(cls, value if 0.0 <= value <=1.0 else 0.0)

    for name, operator in (("__neg__","-"), ("__index__", "index()")):
        message = ("bad operand type for unary {0}: '{{self}}'".format(operator))

    exec("def {0}(self): raise TyperError(\"{1}\".format(self=self.__class__.__name__))".format(name, message))

    def __invert__(self):
        return iFuzzBool(1.0 - float(self))

    def __and__(self, other):
        return iFuzzBool(min(self, other))

    def __repr__(self):
        return f"{self.__class__.__name__}({super().__repr__()})"



me_fuzz = iFuzzBool(.234)
print(-me_fuzz)

预期的结果应该引发 TypeError

标签: pythonpython-3.xmethodsexec

解决方案


不要尝试从 float 继承然后删除方法。定义一个做你想做的事的类,它有一个浮点数作为属性。


推荐阅读