简体   繁体   English

Python类条件:从x输入获取[x,x]输出?

[英]Python class condition: getting an [x,x] output from an x input?

I'm playing around with some interval calculations in Python. 我正在玩一些Python中的间隔计算。 This is an excerpt of what I've written. 这是我所写内容的节选。 I want to include degenerate intervals ie the interval for the real number 1 is [1,1]. 我想包括退化区间,即实数1的区间为[1,1]。

So when I type Interval(1), I want [1,1] returned. 因此,当我键入Interval(1)时,我想返回[1,1]。 But I've defined my interval class in terms of two parameters. 但是我已经根据两个参数定义了间隔类。

I can't make a subclass - it would still expect two parameters. 我无法创建子类-它仍然需要两个参数。 Can anyone point me in the right direction please? 谁能指出我正确的方向? Could I extend the __contains__ in some sense? 我可以在某种意义上扩展__contains__吗?

TLDR : How can I get an [x,x] output from an x input? 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]

Just give RightEndpoint a default value, like None ; 只需给RightEndpoint一个默认值,如None if it is still None in the function, you know no value was assigned to it and thus can be set to the same value as LeftEndpoint : 如果在函数中仍为None ,则您未为其分配任何值,因此可以将其设置为与LeftEndpoint相同的值:

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

Note: if you follow the Python styleguide, PEP 8 , parameter and local variable names should be all lowercase_with_underscores. 注意:如果您遵循Python样式指南PEP 8 ,则参数和局部变量名称应全部为lowercase_with_underscores。 And the __contains__ method should really return True or False , not raise an exception: __contains__方法应该真正返回TrueFalse ,而不引发异常:

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

Note that the __contains__ method can now be expressed as a single test; 注意,现在可以将__contains__方法表示为单个测试。 either num is in the (inclusive) range of left to right , or it is not. 任一num是在(含)范围的leftright ,或不是。

Demo: 演示:

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

You can use *args to pass in a variable number of arguments, then just assign RightEndpoint dynamically: 您可以使用*args传递可变数量的参数,然后只需动态分配RightEndpoint

def __init__(self, *args):
        self.min = args[0]
        if len(args) < 2:
            RightEndpoint = args[0]
        elif len(args) == 2:
            RightEndpoint = args[1]
        else:
            # decide what to do with more than 2 inputs
        self.max = RightEndpoint
        #...


p = Interval(1,2)
print(p) #returns [1,2]
p1 = Interval(1) 
print(p1) #returns [1,1]

(Alternately you can use **kwargs if you want to use keyword arguments instead.) (或者,如果您想使用关键字参数,则可以使用**kwargs 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM