python - 未实现方法
问题描述
我想在 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
解决方案
不要尝试从 float 继承然后删除方法。定义一个做你想做的事的类,它有一个浮点数作为属性。
推荐阅读
- swift - UITextFields 键盘未出现在 UIScrollview 中
- c# - ILogger<> 约定在 Azure Function 托管的服务中不起作用
- javascript - jQuery Burger 菜单不起作用且不可点击
- javascript - 下拉列表移动其他元素
- python - 如何将 .gif 粘贴到 .png 图像上并将生成的文件另存为 .gif?
- css - iPhone 不支持 CSS 网格行
- api - 一段时间后如何删除发布到松弛的消息?
- python - 在 python 中编写正则表达式来匹配两个特定的单词,允许设置单词之间的数量
- c++ - 用于嵌入式系统的 C++ 事件驱动状态机
- python - 如何组合单个数组中的值,由空格分隔(如矩阵)并由方括号 [] 组合