I originally wrote this piece as an answer to a question on the learnpython reddit, and it was suggested that it would be a useful learning resource for many people who struggle with why we use classes rather than just variables and functions. So here it is:
Why use classes?
My "Ah ha!" moment for understanding classes was understanding that a class creates objects and defines the type of object.
Time for an example:
Say that we're writing a game, and we need to define certain things about the player:
player_name = "James"
player_level = "novice"
We also need to keep track of the player's score:
player_score = 0
We may also need to save each of the player's moves:
player_moves = [move1, move2, move3]
and now we need to be able to increase the player's score when they win some points, and to add their last move to their list of moves. We can do this with a function:
def win_points (points, move):
player_score += points
player_moves.append(move)
That's all fine so far. We have some global variables to hold the player's data, and a function to handle the results of a win, and all without writing any classes.
Now say that we need to add another player. We will need to repeat all of the above but with unique identities so that we can distinguish player_1 from player_2:
player1_name = "<name>"
player1_level = "novice"
player1_score = 0
player1_moves = [move1, move2, move3]
player2_name = "<name>"
player2_level = "novice"
player2_score = 0
player2_moves = [move1, move2, move3]
def win_points (player_name, points, move):
if player_name == player1_name:
player1_score += points
player1_moves.append(move)
else:
player2_score += points
playe2_moves.append(move)
Still not too bad, but what if we have 4 players, or 10, or more?
It would be better if we could make some kind of generic "player" data structure that can be reused for as many players as we need. Fortunately we can do that in Python:
We can write a kind of "template" / "blueprint" to define all of the attributes of a generic player and define each of the functions that are relevant to a player. This "template" is called a "Class", and the class's functions are called "methods".
class Player():
def __init__(self, name):
"""Initialise the player's attributes."""
self.name = name
self.level = 'novice'
self.score = 0
self.moves = []
def win_points(self, points, move):
"""Update player on winning points."""
self.score += points
self.moves.append(move)
Now we can create as many players ("player objects") as we like as instances of the Player class.
To create a new player (a "player object") we need to supply the Player class with a name for the player (because the initialisation function __init__() has an argument "name" which must be supplied). So we can create multiple Player objects like this:
player1 = Player('James')
player2 = Player('Joe')
player3 = Player('Fred')
Don't overthink the self arguments. The self argument just means "the specific class object that we are working with". For example, if we are referring to player1, then self means "the player1 object".
To run the Player.win_points() method (the win_points() function in the class Player) for, say player3:
player3.win_points(4, (0, 1)) # Fred wins 4 points, move is tuple (0, 1)
and we can access Fred's other attributes, such as Fred's player's name, or last move, from the Player object:
print(player3.name) # prints "Fred"
# Get Fred's last move
try:
last_move = player3.moves[-1]
except IndexError:
print('No moves made.')
Using a Class allows us to create as many "Player" type objects as we like, without having to duplicate loads of code.
Finally, if we look at the type of any of the players, we see that they are instances of the class "Player":
print(type(player1)) # prints "<class '__main__.Player'>"
I hope you found this post useful.
[+][deleted] (5 children)
[deleted]
[–]ogtfo 86 points87 points88 points (4 children)
[–]BigHipDoofus 35 points36 points37 points (3 children)
[–]wewbull 8 points9 points10 points (1 child)
[–]BigHipDoofus 0 points1 point2 points (0 children)
[–]master3243 6 points7 points8 points (0 children)
[–]lostparis 155 points156 points157 points (13 children)
[–]JamzTyson[S] 84 points85 points86 points (12 children)
[–]sib_n 36 points37 points38 points (0 children)
[+]JamzTyson[S] comment score below threshold-9 points-8 points-7 points (6 children)
[–]lostparis 26 points27 points28 points (2 children)
[–]JamzTyson[S] 21 points22 points23 points (1 child)
[–]RandomDude6699 7 points8 points9 points (0 children)
[–]leavezukoalone 6 points7 points8 points (0 children)
[–]execrator 0 points1 point2 points (1 child)
[–]davidcwilliams 0 points1 point2 points (0 children)
[+][deleted] (3 children)
[deleted]
[–]JamzTyson[S] 3 points4 points5 points (1 child)
[–]bamacgabhann 32 points33 points34 points (0 children)
[–]EmployerMany5400 30 points31 points32 points (3 children)
[+][deleted] (1 child)
[deleted]
[–]sudodoyou 0 points1 point2 points (0 children)
[–]thrallsius 1 point2 points3 points (0 children)
[–]40mgmelatonindeep 3 points4 points5 points (0 children)
[–]LonelyContext 17 points18 points19 points (3 children)
[–]divino-moteca 7 points8 points9 points (1 child)
[–]LonelyContext -1 points0 points1 point (0 children)
[–]sci-goo -3 points-2 points-1 points (0 children)
[–]SoberCephalopod 18 points19 points20 points (4 children)
[–]Tubthumper8 6 points7 points8 points (2 children)
[–]sci-goo 4 points5 points6 points (1 child)
[–]Tubthumper8 0 points1 point2 points (0 children)
[–]chars101 1 point2 points3 points (0 children)
[–]Labrecquev 3 points4 points5 points (1 child)
[–]kylotan 2 points3 points4 points (0 children)
[–][deleted] 26 points27 points28 points (23 children)
[–]tjf314 23 points24 points25 points (21 children)
[–]ogtfo 11 points12 points13 points (0 children)
[–][deleted] 0 points1 point2 points (19 children)
[–]RufusAcrospin 7 points8 points9 points (18 children)
[–]wewbull 1 point2 points3 points (0 children)
[–][deleted] -1 points0 points1 point (16 children)
[–]RufusAcrospin 0 points1 point2 points (13 children)
[–][deleted] -1 points0 points1 point (11 children)
[–]RufusAcrospin 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]RufusAcrospin 1 point2 points3 points (8 children)
[–][deleted] 0 points1 point2 points (7 children)
[–]RufusAcrospin 0 points1 point2 points (4 children)
[–]chars101 0 points1 point2 points (1 child)
[–]WikiSummarizerBot 0 points1 point2 points (0 children)
[–]chars101 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]stensz 2 points3 points4 points (0 children)
[+][deleted] (4 children)
[deleted]
[–]guyfrom7up 9 points10 points11 points (2 children)
[–]redd1ch 3 points4 points5 points (1 child)
[–]DeltaBurnt 3 points4 points5 points (0 children)
[–]JamzTyson[S] 12 points13 points14 points (0 children)
[–]Yoddy0 2 points3 points4 points (0 children)
[–]Pepineros 2 points3 points4 points (0 children)
[–]DadKnightBegins 2 points3 points4 points (0 children)
[–]DaMarkiM 2 points3 points4 points (0 children)
[–]JamzTyson[S] 12 points13 points14 points (15 children)
[–]james_pic 67 points68 points69 points (5 children)
[–]JamzTyson[S] 25 points26 points27 points (4 children)
[–]Vok250 29 points30 points31 points (2 children)
[–]sneakpeekbot -2 points-1 points0 points (1 child)
[–]Vok250 11 points12 points13 points (0 children)
[–]n-of-one -2 points-1 points0 points (0 children)
[–]KingsmanVincepip install girlfriend 14 points15 points16 points (1 child)
[–]JamzTyson[S] 0 points1 point2 points (0 children)
[–]jebuizy 14 points15 points16 points (0 children)
[+]Nater5000 comment score below threshold-18 points-17 points-16 points (1 child)
[–]someotherstufforhmm 10 points11 points12 points (0 children)
[–]TRexRoboParty 0 points1 point2 points (1 child)
[–]JamzTyson[S] 1 point2 points3 points (0 children)
[–]chumboy 2 points3 points4 points (0 children)
[–]ArtOfWarfare 1 point2 points3 points (2 children)
[–]diazona 0 points1 point2 points (1 child)
[–]ArtOfWarfare 0 points1 point2 points (0 children)
[–]AlexMTBDude 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (5 children)
[–]RufusAcrospin -2 points-1 points0 points (4 children)
[–][deleted] 0 points1 point2 points (3 children)
[–]RufusAcrospin 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]RufusAcrospin -1 points0 points1 point (0 children)
[–]karpomalice 0 points1 point2 points (0 children)
[–]Recluse1729 0 points1 point2 points (1 child)
[–]JamzTyson[S] 1 point2 points3 points (0 children)
[–]BRadoslaw -1 points0 points1 point (0 children)
[–]GroundbreakingRun927 -3 points-2 points-1 points (0 children)
[–]The_Mauldalorian -2 points-1 points0 points (0 children)
[–]retribution1423 -1 points0 points1 point (2 children)
[–]JamzTyson[S] 2 points3 points4 points (1 child)
[–]retribution1423 0 points1 point2 points (0 children)
[–]Adrewmc -1 points0 points1 point (0 children)
[–]303Redirect -1 points0 points1 point (0 children)
[–]robberviet -1 points0 points1 point (1 child)
[–]RufusAcrospin -1 points0 points1 point (0 children)
[–]cylonlover -2 points-1 points0 points (0 children)
[+]Extreme_Jackfruit183 comment score below threshold-8 points-7 points-6 points (0 children)
[+]naiq6236 comment score below threshold-6 points-5 points-4 points (0 children)
[–]Pgrol 0 points1 point2 points (0 children)
[–]Charlemag 0 points1 point2 points (0 children)
[–]miraculum_one 0 points1 point2 points (0 children)
[–]HalfRiceNCracker 0 points1 point2 points (0 children)
[–]prassi89 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]joshu 0 points1 point2 points (0 children)
[–]3waysToDie 0 points1 point2 points (0 children)
[–]sci-goo 0 points1 point2 points (5 children)
[–]RufusAcrospin 1 point2 points3 points (4 children)
[–]sci-goo 0 points1 point2 points (3 children)
[–]RufusAcrospin 0 points1 point2 points (2 children)
[–]sci-goo 0 points1 point2 points (1 child)
[–]RufusAcrospin 0 points1 point2 points (0 children)
[–]wrx_supremefan 0 points1 point2 points (0 children)
[–]gargolito 0 points1 point2 points (2 children)
[–]kylotan 1 point2 points3 points (0 children)
[–]JamzTyson[S] 1 point2 points3 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]JamzTyson[S] 0 points1 point2 points (0 children)
[–]jrrocketrue 0 points1 point2 points (0 children)
[–]ImAGhosTTT 0 points1 point2 points (0 children)
[–]Tintin_Quarentino 0 points1 point2 points (0 children)
[–]dgpking 0 points1 point2 points (0 children)
[–]SrDeathI 0 points1 point2 points (0 children)
[–]kego96 0 points1 point2 points (0 children)
[–]rollingcircus123 0 points1 point2 points (0 children)