Let’s look at building a simple class. A dice class.
If we think of a dice, we know there are different types. We’ll look at something simple like a standard six sided dice.
Defining the Class
We need to define the class. This starts off similar to a lot of Python. We’ll have a class keyword, and our class name followed by a colon. Everything inside of the class is indented to show it is part of the class definition.
import random
class Dice :
# all variables and methods are indented
Standard practice is to capitalize the first letter of your class name. This isn’t a requirement, but helps with identifying classes easily. When we create an object from the class, it will start with a lower case letter.
Adding a Constructor
Next we will want to create a constructor. A constructor is a special method which is automatically called when we create an object from a class. We can use it to set default values and prepare our object for use in the program.
A constructor always has a special name. This will vary depending upon the language you are programming in. In Python it is __init()__ (notice that init has two underscores before and after init()).
Any method that is part of a class, has to have a parameter called self. This is so the method can reference items within the object, itself essentially, and how it keeps track of data from one object of class Dice, vs. another object of class Dice, or any other class.
In our class, we’ll reference a variable called value, giving it a default value, and allowing it to be accessed in other methods because we call it here.
import random
class Dice :
# all variables and methods are indented
def __init__(self) :
self.value = random.randint(1,6)
Notice how we still use the def keyword to define the start of our method, and create it just as we would a function? This is an important step in the process. It keeps things similar, so what you learned in Python as a procedural language stays the same, and makes it easier to learn/use.
Adding Methods
Next we start to think about what else our Dice can do. If you’ve played games with dice, (Yahtzee, Monopoly, etc) you know that you need to be able to roll the dice to change it’s value. You also know you need to be able to get the value of the Dice.
Now in real life, it’s easy to read/see the dice value. However, in the computer, we will use a get_value() method. With get_value(), we will return the value, not print it.
Printing data should not be done inside of the class in most cases. That should be handled in the main program – because we want our class to be reusable. That means it should be able to be used in different applications, not just our one example.
import random
class Dice :
# all variables and methods are indented
def __init__(self) :
self.value = random.randint(1,6)
def roll(self) :
self.value = random.randint(1,6)
def get_value(self) :
return self.value
Notice how in each method was pass the self parameter. Also notice how when we reference value, it is always self.value. That is because it is the object’s variable, which will continue to exist while the object does, not a variable in the method which will be lost as soon as the method completes it’s execution.
Using our Class
If you type this into your code, and run it, nothing will happen however. The code will just sit there. We have to create an instance of the class, and run it.
def main() :
my_dice = Dice() # create an instance of the dice
for num in range(25) :
my_dice.roll()
print('Roll', str(num +1) + ':', my_dice.get_value())
main()
Here we create a Dice object, and call it my_dice. Then we run a for loop, 25 times. With each loop iteration, we roll the dice, and print out the results we get from the get_value() method.
You should see 25 random values of the dice printed to the screen.
This just adds a level of protection to our class, both in making sure only proper values are set, as well as making sure that if we change how things are stored internally, that it doesn’t break other people’s code.
Building your first Python Class was originally found on Access 2 Learn