Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Dice Roller Giving a Hand

26,612 Points

Why 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?

They are there for the case that the caller of the function uses them, like he does later with favorite weapon, scar...

26,612 Points

I'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!!')

        for x in range(rolls):

2 Answers

Ari Misha
Ari Misha
19,274 Points

Hiya 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. (:

I 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
Joao Cid
7,706 Points

Well, that is also my interpretation, which makes the code less prone to runtime errors, though still running towards the goal it is intended to.