Writing a Proper Python Class

When you write a class there are a lot of things to consider. Especially if you are going to release your class for others to use. In this section we will build a simple class to represent a die that you can roll, and a cup to contain a bunch of dice. We will incrementatlly improve our implementations to take into consderation the following aspects of desiging a class that works well in the Python ecosystem.

If the class is a container for other classes then there are some further considerations:

A Basic implementation of the MSDie class

Lets start with a really simple implementation of the MSDie class, and we’ll improve it one step at a time. We want to make our die a bit flexible so the constructor will allow us to specify the number of sides.

This is a nice starting point. In fact, for some assignments this might be all you need. We have a class, we can construct a die, and roll it, and print out the current value. Sort of… It would be nicer if we could just print(my_die) and have the value of the die show up without having to know about the instance variable called current_value.

Lets fix up the representation to make printing and interacting with the die a bit more convenient. For this we will implement the __str__ and __repr__ magic methods.

Notice that when we print a list of objects, the repr is used to display those objects. Having a good repr makes it easier to debug with simple print statements.

You have attempted of activities on this page