Object Attributes

Attributes are variables that belong to an object.


Objective: create a game object that can keep track of a score.

Example Code:

class game:
   pass

mygame = game()
mygame.score = 0
mygame.score += 250
print(mygame.score)

The game class includes no instructions: pass means “do nothing.” This means that the game class is totally generic – it has no class methods or attributes. We’re keeping things simple right now!

The following line creates a game object called mygame:

mygame = game()

To begin with, mygame doesn’t do anything or contain any data.

The following creates a variable named score as part of the mygame object and initializes it to zero:

mygame.score = 0

Now the score attribute can be modified and accessed:

mygame.score += 250
print(mygame.score)

To access an object’s variables, type the object name , followed by a dot, then the attribute name.

An object can have many attributes. They can be different types.

mygame.player_name = "Potato"
mygame.difficulty = "easy"
mygame.inventory = ['spatula', 'towel']
mygame.experience = 100

These commands add four attributes to the mygame object, including Stringlist, and int types.

Different Objects, Different Values

Let’s create two game objects:

g1 = game()
g2 = game()

Each of these can have different scores:

g1.score = 200
g2.score = 9000

Each object has its own separate identity, so it makes sense that each object can have different values for each of its own attributes.