Home Create an Interval class with desired format

# Create an Interval class with desired format

Sam
1#
Sam Published in 2017-12-05 23:23:35Z
 Im trying to create a class called Interval that if given 1 parameter a, it creates it in the format [a,a], and if given 2 parameters a and b, it creates it in the format [a,b]. See the following code class Interval(): def __init__(self,left,*args): if args: self.left=left self.right=args else: self.left=left self.right=left def __repr__(self): return("[{},{}]".format(self.left,self.right))  Now when i have only one parameter it prints it out in the desired format, but with 2 parameters i get a paranthesis inside the brackets, see below:  a = Interval(1) b = Interval(2,4) print (a) print (b)  Prints out:  [1,1] [2,(4,)]  Why does this happen? Any help appreciated, thanks.
epinal
2#
 'args' is a tuple, that's why you get the paranthesis. class Interval(): def __init__(self,left,*args): if args: self.left=left self.right=args[0] else: self.left=left self.right=left def __repr__(self): return("[{},{}]".format(self.left,self.right)) 
 To be as generic as possible, you can try this: class Interval(): def __init__(self,left,*args): if args: self.left=left self.right=args else: self.left=left self.right=left def __repr__(self): return("[{},{}]".format(self.left,','.join(map(str, self.right)))) i = Interval(4, 4) print(i)  Output: [4,4]