In your small example it makes no difference between the first and second example. Either is fine.
The difference becomes important with real world examples, such as when you want to have multiple instances of a class. For example, consider a game. If you are a single-player game, your first example is fine. Create the class, and reference the values directly in the class.
However, what do you do when you have a multiplayer game and variable1
represents the player's score? You can create a Player1
class and a Player2
class, and your first example continues to work. Now what do you do if in addition to score, you have 100 other attributes? Do you have two identical classes that are defined exactly the same? What if you want to support 100 players? Or 1000? Do you create 1000 classes that are identical, only differing by the name of the class?
This is why classes are so powerful: you define the class exactly once, and then you can create as many instances of that class that you want. Whether you have one player or 1000, you only have to define the player class once, yet each class has it's own data 1
So, for simple examples, why go to the trouble of creating instances? The reason is that it builds good habits. If you get into the habit of creating classes and instantiating them, when the time comes to make a more complex application you won't have to change the way you work.
Bottom line: for any non-trivial definition of an object, your code will be much easier to maintain if you have a single class with multiple instances.
1 if we literally use your example code, each player will share the same score. However, if you create classes with instance attributes rather than class attributes, each player will get its own score.