首页 > 解决方案 > 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]

标签: python

解决方案


只需给出RightEndpoint一个默认值,例如None; 如果它仍在None函数中,则您知道没有为其分配任何值,因此可以设置为与以下相同的值LeftEndpoint

def __init__(self, LeftEndpoint, RightEndpoint=None):
    if RightEndpoint is None:
        RightEndpoint = LeftEndpoint

注意:如果您遵循Python 样式指南,PEP 8,参数和局部变量名称应该都是小写的_with_underscores。并且该__contains__方法应该真正返回Trueor 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的(包括)范围内,要么不在。leftright

演示:

>>> Interval(1, 2)
[1, 2]
>>> Interval(1)
[1, 1]
>>> 11 in Interval(42, 81)
False
>>> 55 in Interval(42, 81)
True

推荐阅读