Python: *args, grouped by type
Problem Description:
I have a class __init__
that accepts variable length arguments. I am trying to figure out how to separate the *args
into str
, and floats/ints
.
So, for example, in my mind that might look like:
class Example():
def __init__(self, *legs, *vals, named_input: float, named_input_2: str):
*legs
are a string. *vals
are floats & ints.
My goal is that the user can do:
a = Example('1y', '5y', named_input = 100, named_input_2 = 'setting_1')
a.legs = ['1y', '5y']
a.vals = []
a = Example('1y', '5y', 15, named_input = 100, named_input_2 = 'setting_1')
a.legs = ['1y', '5y']
a.vals = [15]
a = Example('1y', 0, 15, 30, named_input = 100, named_input_2 = 'setting_1')
a.legs = ['1y']
a.vals = [ 0, 15, 30,]
At least 1 *leg
must always be supplied. vals
can be None
though.
Solution – 1
Overcomplicated it.. just had to do this:
class test():
def __init__(self, *args):
self.legs = []
self.vals = []
for x in args:
if type(x) in [str]:
self.legs.append(x)
elif type(x) in [float, int]:
self.vals.append(x)