0

I have a class which takes two numbers and prints them in a list

class Numbers():

    def __init__(self, l, r):

        self.l = l
        self.r = r

    def __str__(self):
        print([self.l, self.r])

ex:

N = Numbers(1, 3) #[1, 3]

Now, I need to extend the class so that it can be initialized with only one value

N2 = Numbers(2) #[2, 2]

Right now I'm a bit clueless on how to proceed, any help is appreciated

J.st
  • 3
  • 2

3 Answers3

1

You can simply use a default parameter:

class Numbers():

    def __init__(self, l, r=None):

        self.l = l
        if r is None:
            self.r = l
        else:
            self.r = r

    def __str__(self):
        return str([self.l, self.r])

print(Numbers(1, 2))
# [1, 2]
print(Numbers(3))
# [3, 3]
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

How about this:

def __init__(self, l, r = None):

    self.l = l
    if r is None:
        self.r = l
    else:
        self.r = r

As others already pointed out, you'll need to modify your __str__ method as well, to be something like this:

def __str__(self):
    return str(self.l) + "," + str(self.r)
Ivan
  • 56
  • 4
0

Try this:

class Numbers:

    def __init__(self, l, r=None):
        self.l = l
        self.r = r if r else l

    def __str__(self):
        return str([self.l, self.r])

ex:

n1 = Numbers(3, 5)
print(n1)  # [3, 5]
n2 = Numbers(2)
print(n2)  # [2, 2]
Oleksii Filonenko
  • 1,551
  • 1
  • 17
  • 27