Python Object-Oriented Python Dice Roller Giving a Hand

Nicholas Abate
Nicholas Abate
1,643 Points

self.append, die_class(), and self.sort

What is self.append(die_class()) appending to?

Why does die_class have () at the end of it?

What is self.sort() sorting? No list is being passed to it.

class Hand(list):
    def __init__(self, size = 0, die_class = None, *args, **kwargs):
        if not die_class:
            raise ValueError("You must provide a die class")
        super().__init__()

    for _ in range(size):
        self.append(die_class())
    self.sort()

2 Answers

Steven Parker
Steven Parker
201,913 Points

In a class, "self" refers to the current instance. In this case the"self" would be a Hand, which is a specialized type of list. So the "append" method is inherited from "list".

When you create a new instance, you put parentheses after the class name (or the variable that refers to the class). So "die_class()" creates a new instance of the class that was passed in as a required argument.

The "sort" method is also inherited from "list", so "self.sort()" sorts the current instance (which is a "Hand" and therefore also a list).

Nicholas Abate
Nicholas Abate
1,643 Points

So if we are to perform some operation to an instance, it's as self.____? It's not all that abstract I guess, just something I never thought of. Everything we've done with classes so seem to be with instance variables and not the instance as a whole.

So I guess that is the subtly that I missed. A variable can be created to call a class? And the syntax is the same as calling that class?

Steven Parker
Steven Parker
201,913 Points

That's right, a variable can represent the class itself or an instance of the class.