Python Classes: A Beginner's Guide to OOP
๐ Quick Info Topic: Classes and objects in Python Target Audience: Beginners who know functions and dictionaries Goal: Understand why classes exist and how to write one 1. Introduction "For weeks, I stored everything in dictionaries. Then I had 10 players in a game, each with a name, score, and level โ and I had to update all of them manually. That's when I learned about classes." 2. The Problemโฆ
1. Introduction
Initially, the author managed game player data using dictionaries, but found the process cumbersome when scaling to 10 players with attributes like name, score, and level. This prompted the author to learn about classes.
2. The Problem (Using Dictionaries for Everything)
The author created separate dictionaries for each player, such as player1, player2, and player3. Each dictionary contained keys for name, score, and level. However, this approach lacked structure, made it easy to make typos, and was difficult to scale.
3. The Solution (With Classes)
The author then used classes to define a Player object. This created a structured way to represent players with data (name, score, level) and methods (add_score). By using classes, each player became an individual object with its own data and methods, making the code more scalable and easier to maintain.
4. How It Works (Line By Line)
The class definition starts with "class Player:". The constructor method, "__init__", runs automatically when a new player object is created. It takes parameters for name, score, and level, storing them as instance variables using "self". The "add_score" method is defined to increase the player's score by a specified amount.
5. What is self?
The "self" keyword is used in Python to differentiate between instance variables and class variables. When calling a method on an object, like "player1.add_score(10)", Python internally calls "Player.add_score(player1, 10)". This means "self" refers to the object the method was called on, in this case, player1.
6. Real Example (My Practice)
The author demonstrates the class definition in action by creating a BankAccount class with methods for depositing and withdrawing funds, as well as displaying the balance. By creating an instance of the class (account = BankAccount(Ali, 100)), the author is able to interact with the object using its methods, resulting in the expected output of Ali's balance being $120 after depositing and withdrawing funds.
Written by urgent.news from Dev.to's reporting โ not their text. Machine-written โ may contain errors; check the original before relying on it.