Calmcode - objects: init

Initialization of Python Objects

1 2 3 4 5 6 7 8 9 10

The first step of creating an object in Python is to create a class. Here's some boilerplate for that:

class Dice:
    def __init__(self, probs):
        self.probs = probs

If you've never seen this before it may look a bit strange. So let's go over a few things:

  • First, the class keyword tells Python we're creating a new type of object. Just like how Python has built-in types like strings and lists, we can create our own types. Here, we're making a new type called Dice.
  • The init function (pronounced "dunder init" - short for double underscore init) is special in Python. It's called when we create a new dice object, and it sets up the initial state. Think of it as the setup instructions for our dice.
  • When we create a dice object, self refers to that specific dice. Dice is a class, but it will create an object and self refers to a created object.
  • By writing self.probs = probs, we're storing the probabilities that were passed in so we can use them later. Every dice object will have its own probs that we can access.