Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialhamsternation
26,616 PointsWhy does Kenneth pass in the *args and **kwargs if we don't need them?
What's the point of passing in the *args and **kwargs if we don't need them or even as he said he couldn't think of a reason to use them?
hamsternation
26,616 PointsI'm not sure what I'm missing but, how might someone use the *args, or **kwargs in this case?
class Hand(list):
def __init__(self, rolls=0, dice_val =None, *args, **kwargs):
if not dice_val:
raise ValueError('YOU HAVE TO PUT A DICE VAL IN THERE!!')
super().__init__()
for x in range(rolls):
self.append(dice_val())
self.sort()
2 Answers
Ari Misha
19,323 PointsHiya Michael! You can always use "setattr" method and assign 'em values. Here is the code for using setattr on your kwargs:
for keys, values in kwargs.items():
setattr(self, keys, value)
Put this code in your init method in order to initialize the object with any no. of arguments. Also remember the zen of Python or guidelines for writing Python codes better , "explicit is better than implicit". So yeah being explicit is considered the best practice in Python.
I hope it helped. (:
Ewerton Luna
Full Stack JavaScript Techdegree Graduate 24,031 PointsI think he uses *args and **kwargs even in the case we're not using them because, otherwise, if the user of the code passes any not needed argument it would cause an TypeError saying that he exceeded the number of arguments of the class.
But we solve this problem using args and kwargs as parameters because the code runs without error for whatever number of arguments passed to the class, since they will all be caught by *args and **kwargs. Since we won't use them, we don't pass these arguments further.
That is my interpretation of this. I'm not entirely sure if I'm right though.
Hope it helped you!
Joao Cid
7,706 PointsWell, that is also my interpretation, which makes the code less prone to runtime errors, though still running towards the goal it is intended to.
dojewqveaq
11,393 Pointsdojewqveaq
11,393 PointsThey are there for the case that the caller of the function uses them, like he does later with favorite weapon, scar...