Skip to content
Ryan James
Menu

← Python10 min read

Class Design

For those of you that have never used classes in programming before I'll try to do my best to explain them. One way to look at programming concepts is that we are constantly abstracting something. It starts with using a variable to represent a piece of data. Then you go further and use lists and arrays.

Class Design

Intro to Classes

For those of you that have never used classes in programming before I’ll try to do my best to explain them. One way to look at programming concepts is that we are constantly abstracting something. It starts with using a variable to represent a piece of data. Then you go further and use lists and arrays. You can also use functions to manipulate all of this data with a single call. Classes can take all of these abstractions and mold them into one abstraction. Classes are a way of wrapping variables, data types, and functions into a single thing which is called an object. When you create an instance of a class, you are creating an object. That is why using classes in programming is referred to as Object-Oriented Programming (OOP).

For this post, instead of giving multiple examples of what I’m trying to show you, we’re going to use just one example and go through it piece by piece. We are going to build a deck of cards in Python using classes. We’ll go through what a Constructor Method is and how to change the default String output of a class as well. Let’s start with an example of a class:

class Card:
    def __init__(self):
        self.suit = ""
        self.number = ""
        self.points = 0

In the example shown above the class, called ‘Card’, is created. This class has 3 variables that are part of it. These variables are often referred to as Instance Variables. The variables are: suit, number, and points. To create an instance of this class you can use the following code:

newCard = Card()

By using that line of code to create a new Card, called newCard, it will create an object that has all 3 instance variables. These can be accessed and manipulated by using: newCard.suit, newCard.number, and newCard.points.

The definition that we created is called a constructor. It constructs the class and initializes all of the instance variables for us. We can change this so that the constructor has parameters, like for example we can have it take an input for the card suit that we want to create.

class Card:
    def __init__(self, suit):
        self.suit = suit
        self.number = ""
        self.points = 0

In the example shown above, we’ve added a ‘suit’ parameter to the constructor. By doing so, now we will create an instance of the card class by using the following code:

newCard = Card("Hearts")

This will create an instance of the Card class, newCard, and its suit variable will be initialized to be “Hearts”.

The data in a class can be printed by just printing the instance of the card Class:

newCard = Card("Hearts")
print(newCard)

When we run the code segment shown above, the data in the class will be printed, but it will not make much sense when you are looking at it. It will return some information about the class type and a hexadecimal location on the computer but that’s about it. What we would really like to see is the value of some of the instance variables that the class is holding. We can do this by overriding the default String method in a class:

class Card:
    def __init__(self, suit):
        self.suit = suit
        self.number = ""
        self.points = 0

    def __str__(self):
        return "{} of {}".format(self.number, self.suit)

Now when you try to print the card, only the String that you typed in the __str__ method will be printed to the screen. Overriding this method makes the class you create very useful since you can create your own custom String statements for it to print.

Now we’re going to take all of this and create some cards! First, use the last Card class example that was shown above. Then below it you want to add a list called ‘deck’. You should have this now:

class Card:
    def __init__(self, suit):
        self.suit = suit
        self.number = ""
        self.points = 0

    def __str__(self):
        return "{} of {}".format(self.number, self.suit)

deck = []

Now we can create a loop that will iterate over this and create our deck of cards. We will create a function that can create 13 cards of each suit. Then we can call that function for each suit. This is what the function should look like:

  def makeSuit(suit):
      for i in range(13):
        card = Card(suit)
        number = i + 2
        if number <= 10:
            card.number = str(number)
            card.points = number
        elif number == 11:
            card.number = "J"
            card.points = 10
        elif number == 12:
            card.number = "Q"
            card.points = 10
        elif number == 13:
            card.number = "K"
            card.points = 10
        elif number == 14:
            card.number = "A"
            card.points = 11
        deck.append(card)

Now once you have a function that can create a suit, you can call this method 4 times, once for each suit and then it’ll have all 52 cards in the deck. Below is the entire program as well as a loop at the end that will print every card in the deck.

class Card:
    def __init__(self, suit):
        self.suit = suit
        self.number = ""
        self.points = 0

    def __str__(self):
        return "{} of {}".format(self.number, self.suit)

deck = []

def makeSuit(suit):
    for i in range(13):
        card = Card(suit)
        number = i + 2
        if number <= 10:
            card.number = str(number)
            card.points = number
        elif number == 11:
            card.number = "J"
            card.points = 10
        elif number == 12:
            card.number = "Q"
            card.points = 10
        elif number == 13:
            card.number = "K"
            card.points = 10
        elif number == 14:
            card.number = "A"
            card.points = 11
        deck.append(card)

makeSuit("Hearts")
makeSuit("Diamonds")
makeSuit("Spades")
makeSuit("Clubs")

for card in deck:
    print(card)

Now that you have a list that contains all the cards in a deck, you can create any card game you want to! It is pretty interesting to think that you can use the list, deck, and it has access to all 52 cards which each have 3 instance variables and its own custom String function that prints the value of the card when called.

Keep coding!
Ryan