Python, class initialization with one value
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
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]
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)
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]
Computing the gradient for a custom TensorFlow op with py_func()
get all files in drive via REST API
Setting an image as a tkinter window background
Displaying A File Using StringVar() // Tkinter Python 3.5
How are features ranked in RFECV in scikit learn(sklearn)?
Solr requests hang when started via python subprocess
How to extract internet email headers from outlook emails?
Tensorboard get blank page
Python Matplotlib Streamplot providing start points
Reduce inner points in numpy coordinate dataset (speed up concave hull)
Blitting several layers pygame
floating and integer power difference in Python
how to skip certain line in text file and keep reading the next line in python?
match key and insert into new column
Python - Storing the values of CSV file in List
Should telegram-code be defined as a message option?