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

asked May 15, 2017 at 17:17
2
  • __str__ is supposed to return a string, not print stuff. Commented May 15, 2017 at 17:44
  • This might be helpful? stackoverflow.com/questions/13382774/… Commented May 15, 2017 at 17:50

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]
answered May 15, 2017 at 17:53
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)
answered May 15, 2017 at 17:58

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]
answered May 15, 2017 at 18:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.