1

I am trying to create a class that takes two numbers as arguments and turn them into an interval. Then with said interval I could use the four basics arithmetic operations on it with another interval. Now I want to take the same class and make it able to take one number only (r) to create a degenerate interval [r,r] but still being able to take two numbers also.

class Interval:
def __init__(self,a,b):
    if b is None:
        self.b=a
        self.a=a
    else:
        self.a=a
        self.b=b
def __add__(self,other):
    a1,b1=self.a, self.b
    if isinstance(other,Interval):
        a2,b2=other.a, other.b
    return Interval(a1+a2,b1+b2)

After running:

i3=Interval(4)
print(i3)

I would get:

TypeError: __init__() missing 1 required positional argument: 'b'

What can I change?

1 Answers1

1

When arguments aren't provided, they don't default to None, they error. So, explicitly provide a default:

def __init__(self, a, b=None):
    # rest of code here
Aplet123
  • 33,825
  • 1
  • 29
  • 55