Python Object-Oriented Python Dice Roller Giving a Hand

hamsternation
hamsternation
23,009 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?

Eric Hamers
Eric Hamers
11,392 Points

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

hamsternation
hamsternation
23,009 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!!')
        super().__init__()

        for x in range(rolls):
            self.append(dice_val())
        self.sort()

2 Answers

Ari Misha
Ari Misha
19,259 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. (:

Ewerton Luna
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ewerton Luna
Full Stack JavaScript Techdegree Graduate 21,174 Points

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.