python - Python 类条件:从 x 输入获取 [x,x] 输出?
问题描述
我正在用 Python 进行一些区间计算。这是我所写内容的摘录。我想包括退化间隔,即实数 1 的间隔是 [1,1]。
因此,当我键入 Interval(1) 时,我希望返回 [1,1]。但是我已经根据两个参数定义了我的区间类。
我不能创建一个子类——它仍然需要两个参数。谁能指出我正确的方向?我可以在某种意义上扩展 __contains__ 吗?
TLDR:如何从 x 输入获得 [x,x] 输出?
from numpy import *
import numpy as np
from pylab import *
class Interval:
def __init__(self, LeftEndpoint, RightEndpoint):
self.min = LeftEndpoint
self.max = RightEndpoint
if LeftEndpoint > RightEndpoint:
raise ValueError('LeftEndpoint must not be greater than RightEndpoint')
def __repr__(self): #TASK 3
return '[{},{}]'.format(self.min,self.max)
def __contains__(self, num):
if num < self.min:
raise Exception('The number is not in the given interval')
if num > self.max:
raise Exception('The number is not in the given interval')
p = Interval(1,2)
print(p) #returns [1,2]
解决方案
只需给出RightEndpoint
一个默认值,例如None
; 如果它仍在None
函数中,则您知道没有为其分配任何值,因此可以设置为与以下相同的值LeftEndpoint
:
def __init__(self, LeftEndpoint, RightEndpoint=None):
if RightEndpoint is None:
RightEndpoint = LeftEndpoint
注意:如果您遵循Python 样式指南,PEP 8,参数和局部变量名称应该都是小写的_with_underscores。并且该__contains__
方法应该真正返回True
or False
,而不是引发异常:
class Interval:
def __init__(self, left, right=None):
if right is None:
right = left
if left > right:
raise ValueError(
'left must not be greater than right')
self.left = left
self.right = right
def __repr__(self):
return f'[{self.left}, {self.right}]'
def __contains__(self, num):
return self.left <= num <= self.right
请注意,该__contains__
方法现在可以表示为单个测试;要么在tonum
的(包括)范围内,要么不在。left
right
演示:
>>> Interval(1, 2)
[1, 2]
>>> Interval(1)
[1, 1]
>>> 11 in Interval(42, 81)
False
>>> 55 in Interval(42, 81)
True
推荐阅读
- javascript - 制作JS游戏,在代码中添加其他对象的地方
- c# - C# linq IQueryable 多重过滤
- ios - FCM 推送通知声音不起作用 IOS(可能重复但没有任何解决方案)
- swift - 更新文档 Firebase 时无限循环
- python - 我想从网站下载所有 PDF,而不是手动下载,但出现 SSL 错误
- java - 休眠标准。用继承构造
- mongodb - 如何将 fetchNewObject 与 update.one ReactiveMongo 一起使用?
- python - 如何将 create-react-app 项目插入现有的 python/flask 应用程序
- forms - MailApp.sendEmail 谷歌应用表的语法和正确的功能位置?
- audio - 使用 GStreamer 从 Pepper 机器人录制音频