Home Create an Interval class with desired format
Reply: 2

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#
epinal Reply to 2017-12-05 23:27:29Z

'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))
Ajax1234
3#
Ajax1234 Reply to 2017-12-05 23:45:15Z

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]
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314032 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO