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

2

3 Answers 3

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]
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.