This is what I'm looking for:
def __init__(self, *args):
list_of_args = #magic
Parent.__init__(self, list_of_args)
I need to pass *args to a single array, so that:
MyClass.__init__(a, b, c) == Parent.__init__([a, b, c])
The *args is a special argument preceded by a star ( * ). When passing the positional arguments 10 , 20 , 30 , and 40 to the function, Python assigns 10 to x , 20 to y , and a tuple (30, 40) to args . It's like tuple unpacking except that the args is a tuple, not a list.
Python has a built-in function str() which converts the passed argument into a string format. The str() function returns a string version of an object. The object can be int , char , or a string . If the object is not passed as an argument, then it returns an empty string.
yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
Nothing too magic:
def __init__(self, *args):
Parent.__init__(self, list(args))
Inside of __init__
, the variable args
is just a tuple with any arguments that were passed in. In fact you can probably just use Parent.__init__(self, args)
unless you really need it to be a list.
As a side note, using super()
is preferable to Parent.__init__()
.
There is this piece of code that I picked up in sentdex tutorials that deals with this:
https://www.youtube.com/watch?v=zPp80YM2v7k&index=11&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ
Try this:
def test_args(*args):
lists = [item for item in args]
print lists
test_args('Sun','Rain','Storm','Wind')
Result:
['Sun', 'Rain', 'Storm', 'Wind']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With